java - Round down a DateTime based on a given Period using Joda-Time -


given period such 3 days, or 5 weeks (a period 1 field type), want round given datetime nearest unit of period (i.e, ignore 5 in '5 days'). examples:

example 1:

  • period: 3 days.
  • datetime: wednesday 4:26 utc (2013-05-15t04:26:00z)
  • rounded datetime: wednesday midnight utc (2013-05-15t00:00:00z)

example 2:

  • period: 5 weeks.
  • datetime: wednesday 4:26 utc (2013-05-15t04:26:00z)
  • rounded datetime: monday midnight utc (2013-05-13t00:00:00z)

my initial idea use period's durationfieldtype getfieldtypes() method, , every matching field in datetime (below largest field), set them zero. however, don't know how datetimefieldtypes datetime , how compare them durationfieldtype.

i prefer not huge if else approach.

example bellow solution in case can express period in days (can modified weeks, months etc.). using datetime joda java library.

unfortunately rounding require see possible issue. need have starting point in time since when calculate periods. in example bellow calculate periods since 1970/01/01 00:00:00 utc. or asking period of 3 days first day of month (year) etc? make more sense.

questions need ask self: happen on leap days?

java method

datetime rounddays(datetime dt, int windowdays) {     duration p = duration.standarddays(windowdays);      long t = dt.getmillis() / p.getmillis() * p.getmillis();     // keep timezone , round floor day     return new datetime(t, dt.getzone()).dayofmonth().roundfloorcopy(); } 

example use:

datetime dt = new datetime(1385578964580l, datetimezone.utc);  system.out.println(rounddays(dt, 3)); system.out.println(rounddays(dt.plusdays(2), 3)); system.out.println(rounddays(dt.plusdays(4), 3)); system.out.println(rounddays(dt.plusdays(6), 3));  // prints data rounded every 3 days // 2013-11-26t00:00:00.000z // 2013-11-29t00:00:00.000z // 2013-11-29t00:00:00.000z // 2013-12-02t00:00:00.000z 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -