Android/Java - Test if date was last month - java

I am working on an app where I store some information between each use, this data essentially boils down to counting the number of times an event has happened today, this week, this month and in the apps lifetime. I store this data in 4 distinct counters I can load/save using SharedPreferences.
Alongside the data I store the "last run time" of the app as a date, my plan was that during load time I will load in the counters then test the stored date against today's date to determine which counters need to be cleared.
Sounds simple right!
After pulling my hair out for a while and going backward and forwards through the Calendar documentation I think I understand them enough to come up with the following:
Calendar last = Calendar.getInstance();
last.setTimeInMillis(lastDate);
Calendar today = Calendar.getInstance();
today.add(Calendar.DATE, -1);
if ( !last.after(today) )
{
today = 0;
}
today.add(Calendar.WEEK_OF_MONTH, -1);
today.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
if ( !last.after(today) )
{
today = 0;
week = 0;
}
today = Calendar.getInstance();
today.add(Calendar.MONTH, -1);
today.set(Calendar.DATE, today.getActualMaximum(Calendar.DATE));
if ( !last.after(today) )
{
today = 0;
week = 0;
month = 0;
}
I think this should be fine, however the issue I have is testing, testing today is easy, however testing the month logic would require either waiting a month, or writing a test case which uses the Calendar API to simulate an old date, however I can't write the test case if my assumptions on how the API works was wrong in the first place!
Therefore, after a large wall of text my question is... does the above block of code look sane, or have I completely mis-understood working with dates in Java?
Thanks!
Edit:
Second pass at the code:
Does this look any more sensible? If I am understanding things correctly I am now attempting to compare the end of the date that was last saved with the very start of today, this week and this month.
Calendar last = Calendar.getInstance();
last.setTimeInMillis(lastDate);
last.set(Calendar.HOUR_OF_DAY, last.getActualMaximum(Calendar.HOUR_OF_DAY));
last.set(Calendar.MINUTE, last.getActualMaximum(Calendar.MINUTE));
last.set(Calendar.SECOND, last.getActualMaximum(Calendar.SECOND));
last.set(Calendar.MILLISECOND, last.getActualMaximum(Calendar.MILLISECOND));
Calendar todayStart = Calendar.getInstance();
todayStart.set(Calendar.HOUR_OF_DAY, todayStart.getActualMinimum(Calendar.HOUR_OF_DAY));
todayStart.set(Calendar.MINUTE, todayStart.getActualMinimum(Calendar.MINUTE));
todayStart.set(Calendar.SECOND, todayStart.getActualMinimum(Calendar.SECOND));
todayStart.set(Calendar.MILLISECOND, todayStart.getActualMinimum(Calendar.MILLISECOND));
// If the last recorded date was before the absolute minimum of today
if ( last.before(todayStart) )
{
todayCount = 0;
}
Calendar thisWeekStart = Calendar.getInstance();
thisWeekStart.set(Calendar.HOUR_OF_DAY, thisWeekStart.getActualMinimum(Calendar.HOUR_OF_DAY));
thisWeekStart.set(Calendar.MINUTE, thisWeekStart.getActualMinimum(Calendar.MINUTE));
thisWeekStart.set(Calendar.SECOND, thisWeekStart.getActualMinimum(Calendar.SECOND));
thisWeekStart.set(Calendar.DAY_OF_WEEK, thisWeekStart.getFirstDayOfWeek());
thisWeekStart.set(Calendar.MILLISECOND, thisWeekStart.getActualMinimum(Calendar.MILLISECOND));
// If the last date was before the absolute minimum of this week then clear
// this week (and today, just to be on the safe side)
if ( last.before(thisWeekStart) )
{
todayCount = 0;
weekCount = 0;
}
Calendar thisMonthStart = Calendar.getInstance();
thisMonthStart.set(Calendar.HOUR_OF_DAY, thisMonthStart.getActualMinimum(Calendar.HOUR_OF_DAY));
thisMonthStart.set(Calendar.MINUTE, thisMonthStart.getActualMinimum(Calendar.MINUTE));
thisMonthStart.set(Calendar.SECOND, thisMonthStart.getActualMinimum(Calendar.SECOND));
thisMonthStart.set(Calendar.DAY_OF_MONTH, thisMonthStart.getActualMinimum(Calendar.MONTH));
thisMonthStart.set(Calendar.MILLISECOND, thisMonthStart.getActualMinimum(Calendar.MILLISECOND));
// If the last date was before the absolute minimum of this month then clear month...
if ( !last.after(thisMonthStart) )
{
todayCount = 0;
weekCount = 0;
monthCount = 0;
}

Other than the readability challenges of using a variable called "today" and setting it to all manner of things that aren't "Today", you're not handling the time.
If it's now 3:20, and something happened at 5:00pm on Jan 31st, we probably want to still count that as happening in January? You should max out the time related fields to the end of the day as well.
For the week thing, that can be a real mess if someone executes in a locale where Sunday is considered the first day of the week. You may want to consider using the system's first day of week, rather than Sunday.
Also it is probably worth noting that this depends explicitly on the use of Calendar.add() to work properly. cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) -1); is NOT the same thing and would be broken.

You should just use Joda-Time. If you do your code becomes:
DateTime oneMonthAgo = new DateTime().minusMonths(1);
DateTime oneWeekAgo = new DateTime().minusWeeks(1);
And so on... It requires no further dependencies than the JDK itself and works on Android. Hope that helps.

Yes, you can use Joda-Time on Android. (From what I've read; I don't use Android)
Yes, you should be using Joda-Time. Far more advanced and useful that the notoriously troublesome java.util.Date and .Calendar classes bundled with Java.
Both your question and the other answers are ignoring the crucial issue of time zone. The time zone defines the meaning of "today" and the beginning/ending of other days.
You should define in plain declarative sentences exactly what you mean by "today", "this week", and "this month". For example, "today"…
Do you mean the last 24 hours?
Do you mean from 00:00:00 and up to but not including 00:00:00 tomorrow, in the UTC/GMT time zone (that is, no time zone offset)?
Do mean from the first moment of today in a given time zone (some offset from UTC) up to but not including the first moment of tomorrow in the same time zone? This may not be 24 hours because of Daylight Saving Time (DST) or other anomalies.
I'm too tired to parse your code. And I shouldn't have to. Before writing such date-time code, you should spell out in plain English what your goal is. Date-time work is surprisingly tricky, so you must be clear on your goals.
Here's some example code in Joda-Time 2.3.
Joda-Time uses the ISO 8601 standard for most defaults. This includes the definition of a week. Monday is first day, numbered 1, and Sunday is last day, numbered 7.
When focusing on a "day" with date-time objects, you may want to start with the first moment of the day. If so, call the withTimeAtStartOfDay method. To get end-of-day, don't. Use the Half-Open approach where you compare up to but not including the first moment of the next day. Explanation is found in other answers on StackOverflow.
Joda-Time offers 3 classes to handle spans of time: Period, Duration, and Interval. Check them all out. When doing comparisons, Joda-Time uses the "Half-Open" approach where the beginning is inclusive and the ending is exclusive. This makes sense when you ponder it. Search StackOverflow for more discussion.
Here's a bit of example code to get you going. I take a set of arbitrary date-time values. Then I define some spans of time as a day, week ago, and month ago. Then I count how many of the values fall into those spans.
String input = "2014-01-02T03:04:05Z";
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
java.util.List<DateTime> dateTimes = new java.util.ArrayList<DateTime>();
DateTime dateTime1 = new DateTime( input, timeZone ); // Parse the string as being in Zulu time zone (UTC). Then adjust to Montréal time.
dateTimes.add( dateTime1 );
dateTimes.add( dateTime1.plusDays( 3 ) );
dateTimes.add( dateTime1.plusWeeks( 1 ) );
dateTimes.add( dateTime1.plusMonths( 1 ) );
DateTime now = new DateTime( timeZone );
dateTimes.add( now );
dateTimes.add( now.minusDays( 1 ) );
dateTimes.add( now.minusDays( 10 ) );
// Spans of time
Interval today = new Interval( now.withTimeAtStartOfDay(), now.plusDays( 1 ).withTimeAtStartOfDay() );
Interval pastWeek = new Interval( now.minusWeeks( 1 ).withTimeAtStartOfDay(), now.plusDays( 1 ).withTimeAtStartOfDay() );
Interval pastMonth = new Interval( now.minusMonths( 1 ).withTimeAtStartOfDay(), now.plusDays( 1 ).withTimeAtStartOfDay() );
int countTotal = dateTimes.size();
int countDay = 0;
int countWeek = 0;
int countMonth = 0;
for ( DateTime dateTime : dateTimes ) {
if ( today.contains( dateTime ) ) {
countDay++;
}
if ( pastWeek.contains( dateTime ) ) {
countWeek++;
}
if ( pastMonth.contains( dateTime ) ) {
countMonth++;
}
}
Dump to console…
System.out.println( "dateTimes: " + dateTimes );
System.out.println( "today: " + today );
System.out.println( "pastWeek: " + pastWeek );
System.out.println( "pastMonth: " + pastMonth );
System.out.println( "countTotal: " + countTotal );
System.out.println( "countDay: " + countDay );
System.out.println( "countWeek: " + countWeek );
System.out.println( "countMonth: " + countMonth );
When run…
dateTimes: [2014-01-01T22:04:05.000-05:00, 2014-01-04T22:04:05.000-05:00, 2014-01-08T22:04:05.000-05:00, 2014-02-01T22:04:05.000-05:00, 2014-03-05T07:40:25.508-05:00, 2014-03-04T07:40:25.508-05:00, 2014-02-23T07:40:25.508-05:00]
today: 2014-03-05T00:00:00.000-05:00/2014-03-06T00:00:00.000-05:00
pastWeek: 2014-02-26T00:00:00.000-05:00/2014-03-06T00:00:00.000-05:00
pastMonth: 2014-02-05T00:00:00.000-05:00/2014-03-06T00:00:00.000-05:00
countTotal: 7
countDay: 1
countWeek: 2
countMonth: 3

Related

Java calculate time by adding specific number of hours, but consider only working hours and non weekend days

For example I have sentTime as an input (25 May 2021 02:00:00 PM) and I need to add reviewTime (10 hours) and calculate releasingTime (considering only working hours(9am-5pm) and non weekend days)
25 May 2021 02:00:00 PM + 10 hours would be 26 May 2021 04:00:00 PM
java.time
I do not know of any easy way to do this. The java.time classes have all the parts needed, but you would have to build up some code to do the calculations.
Be aware that you must account for time zone. On some dates, you will encounter anomalies such as days being 23 or 25 hours long, the clock skipping ahead or dropping behind. One example of such anomalies is Daylight Saving Time (DST), but that is not the only cause. Politicians around the world have shown a penchant for redefining the time-keeping of their jurisdictions for varied reasons.
Here is a brief example to get you started, if you choose to go this route.
Besides the java.time classes built into Java, this code also leverages the ThreeTen-Extra library which adds functionality to java.time. We need that library for two classes here:
A TemporalAdjuster for finding the next working day (skipping Saturday-Sunday). See tutorial on temporal adjusters. Tip: You may want to consider implementing a TemporalAdjuster on your own as part of a real solution — but I'm not sure, just an idea I have not thought through.
Interval class to track a pair of moments as seen in UTC (an offset of zero hours-minutes-seconds). Not required here, but might be useful in further work.
Duration work = Duration.ofHours( 10 );
LocalTime shiftStart = LocalTime.of( 9 , 0 );
LocalTime shiftEnd = LocalTime.of( 17 , 0 );
ZoneId z = ZoneId.of( "America/Chicago" );
ZonedDateTime startOfWork = ZonedDateTime.of( 2021 , 5 , 25 , 14 , 0 , 0 , 0 , z );
// Calculate how much time left in the day to work.
ZonedDateTime endOfDayOne = startOfWork.with( shiftEnd );
Duration untilEndOfDayOne = Duration.between( startOfWork , endOfDayOne );
Duration remainingWork = work.minus( untilEndOfDayOne );
// Determine next work-day.
// Add ThreeTen-Extra library to your project to access the `TemporalAdjuster` for `nextWorkingDay()`.
LocalDate nextWorkDay = endOfDayOne.toLocalDate().with( org.threeten.extra.Temporals.nextWorkingDay() );
ZonedDateTime startOfNextWorkingDay = ZonedDateTime.of( nextWorkDay , shiftStart , z );
ZonedDateTime endOfWork = startOfNextWorkingDay.plus( remainingWork );
org.threeten.extra.Interval workInterval =
org.threeten.extra.Interval.of(
startOfWork.toInstant() ,
endOfWork.toInstant()
);
Dump to console. By default, java.time generates text in standard ISO 8601 formats.
System.out.println( "startOfWork = " + startOfWork );
System.out.println( "work = " + work );
System.out.println( "endOfWork = " + endOfWork );
System.out.println( "workInterval = " + workInterval );
When run.
startOfWork = 2021-05-25T14:00-05:00[America/Chicago]
work = PT10H
endOfWork = 2021-05-26T16:00-05:00[America/Chicago]
workInterval = 2021-05-25T19:00:00Z/2021-05-26T21:00:00Z
Project management software
Project Management software is built to do this very job: Calculate elapsed time for various tasks restricted by working hours and working days. One possible solution is trying to leverage such a library for your purposes.
Assuming sentTime is of type java.util.Date, you can may be use the following code that utilizes Java 8's java.time.LocalDateTime
int reviewTime = 10;
List<DayOfWeek> weekends = Arrays.asList(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY);
LocalDateTime start = sentTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
final int workingHoursStart = 9;
final int workingHoursEnd = 17;
int hoursReviewed = 0;
while(reviewTime > hoursReviewed){
DayOfWeek dayOfWeek = start.getDayOfWeek();
if(weekends.contains(dayOfWeek) || start.getHour() < workingHoursStart || start.getHour() > workingHoursEnd){
start = start.plusHours(1);
continue;
}
start = start.plusHours(1);
hoursReviewed++;
}
Your resultant releasingTime time would be in the start object after the loop finishes iterating.

Java date comparison off by a day

I have a Java method which compares two Dates and returns the number of days between them, but it's off by a day.
Even after I 0 out the hours, min, and sec the calculation is still off.
public long compareDates(Date exp, Date today){
TimeZone tzone = TimeZone.getTimeZone("America/New_York");
Calendar expDate = Calendar.getInstance();
Calendar todayDate = Calendar.getInstance();
expDate.setTime(exp);
todayDate.setTime(today);
expDate.set(Calendar.HOUR_OF_DAY, 0);
expDate.set(Calendar.MINUTE, 0);
expDate.set(Calendar.SECOND, 0);
todayDate.set(Calendar.HOUR_OF_DAY, 0);
todayDate.set(Calendar.MINUTE, 0);
todayDate.set(Calendar.SECOND, 0);
logger.info("Today = " + Long.toString(todayDate.getTimeInMillis()) + " Expiration = " + Long.toString(expDate.getTimeInMillis()));
expDate.setTimeZone(tzone);
todayDate.setTimeZone(tzone);
return (expDate.getTimeInMillis()-todayDate.getTimeInMillis())/86400000;
}
Output
Today = 1453939200030 Expiration = 1454544000000
There's 7 days between 1/28 and 2/4 but this returns 6.
Well, as you can see, you didn't clear the milliseconds, and 1454544000000 - 1453939200030 = 604799970 and dividing by 86400000 gets you 6.99999965277777..., which means 6 when truncated to int.
Now, if you clear the milliseconds too, today becomes 1453939200000, which will lead to you answer 7.
Note: This doesn't mean you're done, because of Daylight Savings Time. With DST, one of the timestamps may be ±1 hour from the other, so you may still get that truncation issue.
This was an answer to your particular issue. Try searching for how to correctly find days between dates in Java.
Today = 1453939200030
The times are given in milliseconds, and it looks like somehow your inputted Date has 30 extra milliseconds on it.
When I subtract the 30 milliseconds, then do the math on a calculator, I get 7 days. With your figures as is, I get 6.9999996527777777777777777777778, and in long math, the decimal figures get truncated to 6.
Zero out the milliseconds also.
expDate.set(Calendar.MILLISECOND, 0);
todayDate.set(Calendar.MILLISECOND, 0);
java.time
The Question and other Answers use outmoded classes. The old date-time classes such as java.util.Date/.Calendar bundled with the earliest versions of Java have proven to be quite troublesome. Those old classes have been supplanted by the java.time framework in Java 8 and later.
As the other Answers point out correctly, the issue is that the start long has 30 on the right side, precluding a whole-day calculation.
Count-Of-Days Definition
Furthermore you must define what you mean by a count-of-days. Do you mean a count by date, so any time on the 3rd of January to any time on the 4th is one day even if the times were a minute before and after midnight? Or do you mean a count of generic 24-hour blocks of time while ignoring the fact that particular days in particular time zones are not always 24-hours long because of Daylight Saving Time (DST) and other anomalies?
Count Days By Date
If you want the former, count by dates, then make use of the LocalDate class (a date-only without time-of-day nor time zone) and the Period class (a span of time defined as a count of years, months, days) found in java.time.
Define your inputs. Use long rather than int. These numbers apparently represent a count of milliseconds since the first moment of 1970 in UTC.
long startMilli = 1_453_939_200_030L;
long stopMilli = 1_454_544_000_000L;
Convert those long numbers into Instant objects, a moment on the timeline in UTC.
Instant startInstant = Instant.ofEpochMilli ( startMilli );
Instant stopInstant = Instant.ofEpochMilli ( stopMilli );
Define the time zone in which you want to consider the calendar dates. Note that time zone is crucial in defining dates. The date is not simultaneously the same around the globe. The date varies by time zone.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
Apply that time zone to each Instant to produce ZonedDateTime.
ZonedDateTime startZdt = ZonedDateTime.ofInstant ( startInstant , zoneId );
ZonedDateTime stopZdt = ZonedDateTime.ofInstant ( stopInstant , zoneId );
To get a Period, we need “local” dates. By “local” we mean any particular locality, a generic date value. The LocalDate class contains no time zone, but the time zone contained with in the ZonedDateTime is applied when determining a LocalDate.
LocalDate startLocalDate = startZdt.toLocalDate ();;
LocalDate stopLocalDate = stopZdt.toLocalDate ();
Define our span of time as a count of generic days, in Period.
Period period = Period.between ( startLocalDate , stopLocalDate );
Interrogate the Period to ask for the number of generic days contained within.
int days = period.getDays ();
Dump to console.
System.out.println ( "milli: " + startMilli + "/" + stopMilli + " | Instant: " + startInstant + "/" + stopInstant + " | ZonedDateTime: " + startZdt + "/" + stopZdt + " | LocalDate: " + startLocalDate + "/" + stopLocalDate + " | period: " + period + " | days: " + days );
milli: 1453939200030/1454544000000 | Instant: 2016-01-28T00:00:00.030Z/2016-02-04T00:00:00Z | ZonedDateTime: 2016-01-27T19:00:00.030-05:00[America/Montreal]/2016-02-03T19:00-05:00[America/Montreal] | LocalDate: 2016-01-27/2016-02-03 | period: P7D | days: 7
Count Of Whole Days
If you want a count of whole days, use the Days class from ThreeTen-Extra. Notice in the output below that we get a count of six (6) days rather than seven (7) as seen above.
ThreeTen-Extra
The ThreeTen-Extra project extends java.time. Run by the same folks who built java.time.
The behavior of the between method is not documented clearly. Experimenting shows that it seems to based on 24-hour chunks of time, not dates. Replace the 030 with 000, and also try replacing in the stopMilli the last 000 with 030, to see the behavior for yourself.
Days daysObject = Days.between ( startZdt , stopZdt );
int daysObjectCount = daysObject.getAmount ();
Dump to console. The P6D string you see in the output was generated according to the formats defined in the ISO 8601 standard. This standard is used by default in java.time for all parsing and generating of textual representations of date-time values. These standard formats are quite sensible and useful so do glance at that linked Wikipedia page.
System.out.println ( "daysObject: " + daysObject + " | daysObjectCount: " + daysObjectCount );
daysObject: P6D | daysObjectCount: 6
To fix my problems, I have zeroed out the milliseconds as mentioned, as well as casted the longs to doubles in order to maintain accuracy and round when necessary.
expDate.setTime(exp);
todayDate.setTime(today);
expDate.setTimeZone(tzone);
todayDate.setTimeZone(tzone);
expDate.set(Calendar.HOUR_OF_DAY, 0);
expDate.set(Calendar.MINUTE, 0);
expDate.set(Calendar.SECOND, 0);
expDate.set(Calendar.MILLISECOND, 0);
todayDate.set(Calendar.HOUR_OF_DAY, 0);
todayDate.set(Calendar.MINUTE, 0);
todayDate.set(Calendar.SECOND, 0);
todayDate.set(Calendar.MILLISECOND, 0);
double diff = ((double)expDate.getTimeInMillis()-(double)todayDate.getTimeInMillis())/86400000;
return Math.round(diff);

Test a date within a day intervall range

I have a date and a number and want to check if this date and this number occurs in a list of other dates within:
+-20 date intervall with the same number
so for example 1, 1.1.2013 and 1,3.1.2013 should reuturn false.
I tried to implement the method something like that:
private List<EventDate> dayIntervall(List<EventDate> eventList) throws Exception {
List<EventDate> resultList = new ArrayList<EventDate>();
for (int i = 0; i < eventList.size(); i++) {
String string = eventList.get(i).getDate();
Date equalDate = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN).parse(string);
for (int j = 0; j < eventList.size(); j++) {
String string1 = eventList.get(i).getDate();
Date otherDate = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN).parse(string1);
if (check number of i with number of j && check Date) {
//do magic
}
}
}
return resultList;
}
The construction of the iteration method is not that hard. What is hard for me is the date intervall checking part. I tried it like that:
boolean isWithinRange(Date testDate, Date days) {
return !(testDate.before(days) || testDate.after(days));
}
However that does not work because days are not takes as days. Any suggestions on how to fix that?
I really appreciate your answer!
You question is difficult to follow. But given its title, perhaps this will help…
Span Of Time In Joda-Time
The Joda-Time library provides a trio of classes to represent a span of time: Interval, Period, and Duration.
Interval
An Interval object has specific endpoints that lie on the timeline of the Universe. A handy contains method tells if a DateTime object occurs within those endpoints. The beginning endpoint in inclusive while the last endpoint is exclusive.
Time Zones
Note that time zones are important, for handling Daylight Saving Time and other anomalies, and for handling start-of-day. Keep in mind that while a java.util.Date seems like it has a time zone but does not, a DateTime truly does know its own time zone.
Sample Code
Some code off the top of my head (untested)…
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Berlin" );
DateTime dateTime = new DateTime( yourDateGoesHere, timeZone );
Interval interval = new Interval( dateTime.minusDays( 20 ), dateTime.plusDays( 20 ) );
boolean didEventOccurDuringInterval = interval.contains( someOtherDateTime );
Whole Days
If you want whole days, call the withTimeAtStartOfDay method to get first moment of the day. In this case, you probably need to add 21 rather than 20 days for the ending point. As I said above, the end point is exclusive. So if you want whole days, you need the first moment after the time period you care about. You need the moment after the stroke of midnight. If this does not make sense, see my answers to other questions here and here.
Note that Joda-Time includes some "midnight"-related methods and classes. Those are no longer recommended by the Joda team. The "withTimeAtStartOfDay" method takes their place.
DateTime start = dateTime.minusDays( 20 ).withTimeAtStartOfDay();
DateTime stop = dateTime.plusDays( 21 ).withTimeAtStartOfDay(); // 21, not 20, for whole days.
Interval interval = new Interval( start, stop );
You should avoid java.util.Date if at all possible. Using the backport of ThreeTen (the long awaited replacement date/time API coming in JDK8), you can get the number of days between two dates like so:
int daysBetween(LocalDate start, LocalDate end) {
return Math.abs(start.periodUntil(end).getDays());
}
Does that help?
You can get the number of dates in between the 2 dates and compare with your days parameter. Using Joda-Time API it is relatively an easy task: How do I calculate the difference between two dates?.
Code:
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
Date startDate = format.parse("1.1.2013");
Date endDate = format.parse("3.1.2013");
Days d = Days.daysBetween(new DateTime(startDate), new DateTime(endDate));
System.out.println(d.getDays());
Gives,
2
This is possible using Calendar class as well:
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
System.out.println(cal.fieldDifference(endDate, Calendar.DAY_OF_YEAR));
Gives,
2
This 2 can now be compared to your actual value (20).

Date Util in java that will explode date range in weeks,month,quarter,year

I am looking for a java library that when given from and to date would return a list of dates in weeks,months,quarter or year which ever is most applicable. I have done this manually and i wanted to know if this is already implemented and tested as a part of a standard package.
Example
Given 1/1/2009 , 1/4/2009 it should give 1/1/2009,1/2/2009,1/3/2009,1/4/2009
Given 1/1/2009 , 1/14/2009 it should give 1/1/2009,1/7/2009,1/14/2009
hope you that is clear :)
The DateTime class provided by Joda Time has methods such as plusDays(int), plusWeeks(int), plusMonths(int) which should help.
Assuming you want to get all the dates between start and end in weeks (pseudocode):
DateTime start = // whatever
DateTime end = // whatever
List<DateTime> datesBetween = new ArrayList<DateTime>();
while (start <= end) {
datesBetween.add(start);
DateTime dateBetween = start.plusWeeks(1);
start = dateBetween;
}
Alternative to Jado is use standart java API
Calendar start = // whatever
Calendar end = // whatever
List<Calendar> datesBetween = new ArrayList<Calendar>();
while (start.compareTo(end) <= 0) {
datesBetween.add(start);
Calendar dateBetween = start.add(Calendar.DAY_OF_MONTH, 7);
start = dateBetween;
}
java.time
The Answer by Dónal using Joda-Time is correct, but outdated. The Joda-Time team has advised that we should migrate to the java.time framework built into Java 8 and later. Much of the java.time functionality has been back-ported to Java 6 & 7 and further adapted to Android.
LocalDate
For a date-only value, without time-of-day and without time zone, use the LocalDate class.
Half-Open
Generally the best practice in handling a span of time is known as Half-Open. In this approach, the beginning of the span is inclusive while the ending is exclusive. So with the example code below, you will see the results do not include the stop date. If you insist on the ending being inclusive, change the date.isBefore ( stop ) to ! date.isAfter ( stop ).
Example code
In its current state, the Question is vague, not addressing issues such as whether to consider if the start date happens to align with start of week or start of month and so on. Another issue: whether to use the Half-Open approach or not. So those issues are left as an exercise for the reader. ;-)
This code counts the number of days in the span of time. If under a week, we loop day-by-day. If over a week, we loop week-by-week. The same logic could be extended to handle month-by-month, quarter-by-quarter, and year-by-year as mentioned in the Question.
LocalDate start = LocalDate.of ( 2016 , Month.JANUARY , 2 );
LocalDate stop = start.plusDays ( 4 );
// LocalDate stop = start.plusWeeks ( 4 );
long days = ChronoUnit.DAYS.between ( start , stop );
List<LocalDate> dates = new ArrayList<> ();
if ( days == 0 ) {
dates.add ( start );// Just one date, as start equals stop.
} else if ( days < 7 ) { // Under a week, count day-by-day.
LocalDate date = start;
do {
dates.add ( date );
// Prep for next loop.
date = date.plusDays ( 1 );
} while ( date.isBefore ( stop ) ); // Using “isBefore” for Half-Open approach where ending is exclusive. For inclusive, use “! isAfter”.
} else if ( days > 7 ) { // Over a week, count week-by-week.
LocalDate date = start;
do {
dates.add ( date );
// Prep for next loop.
date = date.plusWeeks ( 1 );
} while ( date.isBefore ( stop ) ); // Using “isBefore” for Half-Open approach where ending is exclusive. For inclusive, use “! isAfter”.
} else {
// FIXME: ERROR. Should not be possible.
}
Dump to console.
System.out.println ( "start: " + start + " | stop: " + stop + " | dates: " + dates );
When run with the line for stop adding 4 days:
start: 2016-01-02 | stop: 2016-01-06 | dates: [2016-01-02, 2016-01-03, 2016-01-04, 2016-01-05]
When run with the line for stop adding 4 weeks:
start: 2016-01-02 | stop: 2016-01-30 | dates: [2016-01-02, 2016-01-09, 2016-01-16, 2016-01-23]
A sample java implementation using jodatime to create a date split over a large range, with minimal memory footprint.
https://github.com/atulsm/Test_Projects/blob/master/src/DateSplitter.java

In Joda-Time, set DateTime to start of month

My API allows library client to pass Date:
method(java.util.Date date)
Working with Joda-Time, from this date I would like to extract the month and iterate over all days this month contains.
Now, the passed date is usually new Date() - meaning current instant. My problem actually is setting the new DateMidnight(jdkDate) instance to be at the start of the month.
Could someone please demonstrates this use case with Joda-Time?
Midnight at the start of the first day of the current month is given by:
// first midnight in this month
DateMidnight first = new DateMidnight().withDayOfMonth(1);
// last midnight in this month
DateMidnight last = first.plusMonths(1).minusDays(1);
If starting from a java.util.Date, a different DateMidnight constructor is used:
// first midnight in java.util.Date's month
DateMidnight first = new DateMidnight( date ).withDayOfMonth(1);
Joda Time java doc - https://www.joda.org/joda-time/apidocs/overview-summary.html
An alternative way (without taking DateMidnight into account) to get the first day of the month would be to use:
DateTime firstDayOfMonth = new DateTime().dayOfMonth().withMinimumValue();
First Moment Of The Day
The answer by ngeek is correct, but fails to put the time to the first moment of the day. To adjust the time, append a call to withTimeAtStartOfDay.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
org.joda.time.DateTime startOfThisMonth = new org.joda.time.DateTime().dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
org.joda.time.DateTime startofNextMonth = startOfThisMonth.plusMonths( 1 ).dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
System.out.println( "startOfThisMonth: " + startOfThisMonth );
System.out.println( "startofNextMonth: " + startofNextMonth );
When run in Seattle US…
startOfThisMonth: 2013-11-01T00:00:00.000-07:00
startofNextMonth: 2013-12-01T00:00:00.000-08:00
Note the difference in those two lines of console output: -7 vs -8 because of Daylight Saving Time.
Generally one should always specify the time zone rather than rely on default. Omitted here for simplicity. One should add a line like this, and pass the time zone object to the constructors used in example above.
// Time Zone list: http://joda-time.sourceforge.net/timezones.html (Possibly out-dated, read note on that page)
// UTC time zone (no offset) has a constant, so no need to construct: org.joda.time.DateTimeZone.UTC
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
java.time
The above is correct but outdated. The Joda-Time library is now supplanted by the java.time framework built into Java 8 and later.
The LocalDate represents a date-only value without time-of-day and without time zone. A time zone is crucial in determine a date. For any given moment the date varies by zone around the globe.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
Use one of the TemporalAdjusters to get first of month.
LocalDate firstOfMonth = today.with( TemporalAdjusters.firstDayOfMonth() );
The LocalDate can generate a ZonedDateTime that represents the first moment of the day.
ZonedDateTime firstMomentOfCurrentMonth = firstOfMonth.atStartOfDay( zoneId );
Oh, I did not see that this was about jodatime. Anyway:
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
int min = c.getActualMinimum(Calendar.DAY_OF_MONTH);
int max = c.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = min; i <= max; i++) {
c.set(Calendar.DAY_OF_MONTH, i);
System.out.println(c.getTime());
}
Or using commons-lang:
Date min = DateUtils.truncate(date, Calendar.MONTH);
Date max = DateUtils.addMonths(min, 1);
for (Date cur = min; cur.before(max); cur = DateUtils.addDays(cur, 1)) {
System.out.println(cur);
}
DateMidnight is now deprecated. Instead you can do:
LocalDate firstOfMonth = new LocalDate(date).withDayOfMonth(1);
LocalDate lastOfMonth = firstOfMonth.plusMonths(1).minusDays(1);
If you know the time zone use new LocalDate(date, timeZone) instead for greater accuracy.
You can also do .dayOfMonth().withMinimumValue() instead of .withDayOfMonth(1)
EDIT:
This will give you 12/1/YYYY 00:00 and 12/31/YYYY 00:00. If you rather the last of the month be actually the first of the next month (because you are doing a between clause), then remove the minusDays(1) from the lastOfMonth calculation
You can get Start date and end date of month using this:
DateTime monthStartDate = new DateTime().dayOfMonth().withMinimumValue();
DateTime monthEndDate = new DateTime().dayOfMonth().withMaximumValue();

Categories