java Calendar compare incorrect - java

I am comparing 2 Calendar objects in java. This the way i am setting each of them
Calendar calendar1 = Calendar.getInstance();
calendar1.set(2012, 6, 17, 13, 0);
And i am getting the following value from table column '2012-07-17 13:00:00' and setting it into Date Java object and then this Date object i am using to set second Calander object.
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(/*Above date object who value is '2012-07-17 13:00:00'*/);
Now when i compare i expect this to be true since both the Calender object are same
calendar2.compareTo(calendar1) >= 0
but instead i am seeing this is becoming true
calendar2.compareTo(calendar1) < 0
Can somebody help?

The following will give you the idea of what's going on (assuming you are parsing the string to produce the date object for calendar1):
Calendar calendar1 = Calendar.getInstance();
calendar1.set(2012, 6, 17, 13, 0);
System.out.println(calendar1.getTime());
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-07-17 13:00:00");
System.out.println(date);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date);
System.out.println(calendar2.compareTo(calendar1));
calendar1.set(Calendar.SECOND, 0); //setting second to 0
calendar1.set(Calendar.MILLISECOND, 0); //setting millisecond to 0
System.out.println(calendar2.compareTo(calendar1));
Test run result:
Tue Jul 17 13:00:47 CDT 2012
Tue Jul 17 13:00:00 CDT 2012
-1
0

After suggestion from #Bhesh Gurung i used the following
calendar1.set(Calendar.MILLISECOND, 0);
calendar1.set(Calendar.SECOND, 0);
calendar2.set(Calendar.MILLISECOND, 0);
calendar2.set(Calendar.SECOND, 0);
and it worked.

tl;dr
ZonedDateTime.of( // Represent a specific moment using the wall-clock time observed by the people of a specific region (a time zone).
2012 , Month.JULY , 17, 13 , 0 , 0 , 0 , // Hard-code the date and time-of-day, plus zone.
ZoneId.of( "America/Montreal" ) // Specify time zone by Continent/Region name, never by 3-4 letter pseudo-one such as PST or CST.
) // Returns a `ZonedDateTime` object.
.toInstant() // Adjust into UTC.
.equals(
myResultSet.getObject( … , Instant.class ) // Retrieve an `Instant` object for a date-time value stored in your database.
)
Time zone
You do not provide enough info for a definitive answer, but as others suggested you likely are seeing a problem with time zones. Your code does not address this crucial issue explicitly. But, implicitly, your creation of a Calendar item assigns a time zone.
java.time
More importantly, you are using troublesome old date-time classes now supplanted by the java.time classes.
Replace your use use of Calendar with Instant and ZonedDateTime.
For a ZonedDateTime, specify your desired/expected time zone explicitly rather than have the JVM’s current default time zone be applied implicitly. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.of( 2012 , Month.JULY , 17, 13 , 0 , 0 , 0 , z );
Adjust into UTC by extracting a Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = zdt.toInstant() ;
Database
From your database, exchange objects rather than mere strings. As of JDBC 4.2 and later, you can exchange java.time objects.
Most databases store a moment such as the SQL-standard type TIMESTAMP WITH TIME ZONE as a value in UTC. So using an Instant object is usually best.
Store your Instant object’s value.
myPreparedStatement.setObject( … , instant ) ;
Retrieval.
Instant instantDb = myResultSet.getObject( … , Instant.class ) ;
Compare using the Instant methods equals, isBefore, and isAfter.
boolean sameMoment = instant.equals( instantDb ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related

Change the time based on the gmt area on Android

I'm a beginner in android development and I've been searching for hours to find an answer for my question but I didn't really understand anything I found.
The match between 2 teams is starting at 20:00 gmt and I want to make it + - based on the area. For example in germany +1 gmt the time should be 21:00. I only want the hours and minutes format like that.
tl;dr
OffsetDateTime
.of(
LocalDate.of( 2021 , Month.MARCH , 23 ) ,
LocalTime.of( 20 , 0 ) ,
ZoneOffset.UTC
) // Returns a `OffsetDateTime` object.
.atZoneSameInstant(
ZoneId.of( "Europe/Berlin" )
) // Returns a `ZonedDateTime` object.
.toLocalTime() // Returns a `LocalTime` object.
.toString() // Returns a `String` object, with text in standard ISO 8601 format.
21:00
Details
Location does not necessarily correlate to time zone. Users choose their time zone as a preference. Servers should generally be set to UTC (an offset of zero). You can get the JVM’s current default time zone by calling ZoneId.systemDefault. If crucial, you should explicitly ask the user to confirm their desired zone.
I only want the hours and minutes format like that.
Date-time objects are not text, and do not have a "format". Think in terms of the logic needed for handling date-time values rather than in terms of manipulating strings.
starting at 20:00 gmt and I want to make it + - based on the area
Representing that 8 PM in UTC (the new GMT):
LocalDate tomorrow = LocalDate.now( ZoneOffset.UTC ).plusDays( 1 ) ;
LocalTime eightPM = LocalTime.of( 20 , 0 ) ;
OffsetDateTime odt = OffsetDateTime.of( tomorrow , eightPM , ZoneOffset.UTC ) ;
For example in germany +1 gmt the time should be 21:00
Define your desired time zone.
ZoneId z = ZoneId.of( "Europe/Berlin" ) ;
Adjust from the OffsetDateTime to a ZonedDateTime.
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
See that code run live at IdeOne.com.
odt.toString(): 2021-02-17T20:00Z
zdt.toString(): 2021-02-17T21:00+01:00[Europe/Berlin]
The odt & zdt objects seen here both refer to the very same simultaneous moment, the same point on the timeline.
This has all been covered many times before on Stack Overflow. Search to learn more.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
It's not Android specific but just a general question about Java.
Use Calendar and SimpleDateFormat like this:
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.set(2021, 1, 16, 20, 00, 00); // 2021-02-16T20:00:00 GMT
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+01:00"));
System.out.println(simpleDateFormat.format(calendar.getTime()));
Set (input) your date as GMT. Then format it GMT+01:00 with SimpleDateFormat and print (output) it.

Java Timestamp conversion error

Here is my problem with time stamp:
in MySql data base there is a column name creation_date with data type timestamp
the value in the column is 2014-07-04 17:35:07.0
when I am trying to convert it to millisecond using java code, it is showing different behavior
For example
if I fetch it using hibernate and print timestamp.getTime() it is showing 1404484507000
but while doing
Timestamp t=new Timestamp(2014, 7, 4, 17, 35, 7, 0);
System.out.println("t.getTime() - "+t.getTime());
it is showing 61365297907000
What's going wrong here.
Did you read the documentation for the (deprecated) constructor you're calling? In particular:
year - the year minus 1900
month - 0 to 11
I'd strongly advise you not to call that constructor to start with. If you're using Java 8, use java.time.Instant and then java.sql.Timestamp.fromInstant.
Otherwise, you could call the constructor taking a long (number of milliseconds) and then set the nanos part separately.
Note that a value of 1404484507000 represents 14:35:07 UTC, so presumably your database is performing a time zone conversion.
tl;dr
From database.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ; // Most databases including MySQL store a moment in a column of a data type akin to the SQL-standard `TIMESTAMP WITH TIME ZONE` as UTC. So retrieve as a `OffsetDateTime` object, expecting its zone to be set to UTC.
ZonedDateTime zdt = odt.atZoneSameInstant( ZoneId.of( "Pacific/Auckland" ) ) ; // Adjust into any time zone you desire. Same moment, different wall-clock time.
To database.
myPreparedStatement.setObject( // As of JDBC 4.2, exchange java.time objects with your database, not mere integers or strings.
… ,
ZonedDateTime.of(
2014 , 7 , 4 ,
17 , 35 , 7 , 0 ,
ZoneId.of( "Africa/Tunis" ) // Specify the time zone giving context to that date and time – where on earth did you mean 5 PM?
)
.toOffsetDateTime() // Adjust from that zone to UTC.
.withOffsetSameInstant(
ZoneOffset.UTC
)
) ;
java.time
The modern solution uses java.time classes.
LocalDate ld = LocalDate.of( 2014 , Month.JULY , 4 ) ; // Or use integer `7` for July, 1-12 for January-December.
LocalTime lt = LocalTime.of( 17 , 35 , 7 );
To determine a moment, you need more than a date and time-of-day. You need a time zone to provide context. Do you mean 5 PM in Japan, or 5 PM in France, or 5 PM in Québec? Those would be any of three different moments.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Adjust from that zone to UTC.
OffsetDateTime odt = zdt.toOffsetDateTime().withOffsetSameInstant( ZoneOffset.UTC ) ;
As of JDBC 4.2 we can directly exchange java.time objects with a database.
myPreparedStatement.setObject( … , odt ) ;
And retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Notice that at no point did we require the integer count from epoch reference. We used smart objects rather than dumb integers or strings.
As for Hibernate, I an not a user, but I do know it has been updated to work with the java.time classes.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
MySQL uses a different Date format than Java does.
You can conver it from the ResultSet, using the getTime and getDate functions:
String query = "SELECT date FROM bean";
[...]
bean.setDate(toJavaDate(resultSet.getDate(1), resultSet.getTime(1)));
Where the toJavaDate code is:
public java.util.Date toJavaDate(java.sql.Date sqlDate, java.sql.Time sqlTime){
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.YEAR, sqlDate.getYear() + 1900);
calendar.set(Calendar.MONTH, sqlDate.getMonth());
calendar.set(Calendar.DAY_OF_MONTH, sqlDate.getDate());
calendar.set(Calendar.HOUR_OF_DAY, sqlTime.getHours());
calendar.set(Calendar.MINUTE, sqlTime.getMinutes());
calendar.set(Calendar.SECOND, sqlTime.getSeconds());
return calendar.getTime();
}
The reverse operation, in order to save a new Date at the MySQL table:
String query = "UPDATE bean SET date = '" + toSqlDate(bean.getDate());
Where toSqlDate is:
public String toSqlDate(java.util.Date javaDate){
String sqlDate = (javaDate.getYear()+1900)+"-"+javaDate.getMonth()+"-"+javaDate.getDate()+" "
+javaDate.getHours()+":"+javaDate.getMinutes()+":"+javaDate.getSeconds();
return sqlDate;
}
Now you can recheck the milliseconds:
long milliseconds = date.getTime();

Inclusive Date Range check in Joda Time

I am using Joda Time 2.1 library.
I have written a method to compare if a given date is between a date range of not. I want it to be inclusive to the start date and end date.I have used LocalDate as I don't want to consider the time part only date part.
Below is the code for it.
isDateBetweenRange(LocalDate start,LocalDate end,LocalDate target){
System.out.println("Start Date : "
+start.toDateTimeAtStartOfDay(DateTimeZone.forID("EST"));
System.out.println("Target Date : "
+targettoDateTimeAtStartOfDay(DateTimeZone.forID("EST"));
System.out.println("End Date : "
+end.toDateTimeAtStartOfDay(DateTimeZone.forID("EST"));
System.out.println(target.isAfter(start));
System.out.println(target.isBefore(end));
}
The output of above method is :
Start Date: 2012-11-20T00:00:00.000-05:00
Target Date: 2012-11-20T00:00:00.000-05:00
End Date : 2012-11-21T00:00:00.000-05:00
target.isAfter(start) : false
target.isBefore(end) : true
My problem is target.isAfter(start) is false even if the target date and start are having the same values.
I want that target >= start but here it considers only target > start.
I want it inclusive.
Does it mean that isAfter method finds a match exclusively ?
I have gone through the javadoc for Joda Time, but didn't found anything about it.
Yes, isAfter is exclusive, otherwise it should probably have been named isEqualOrAfter or something similar.
Solution: Use "not before" instead of "after", and "not after" instead of "before".
boolean isBetweenInclusive(LocalDate start, LocalDate end, LocalDate target) {
return !target.isBefore(start) && !target.isAfter(end);
}
tl;dr
Joda-Time has been supplanted by the java.time classes and the ThreeTen-Extra project.
The LocalDateRange and Interval classes representing a span-of-time use the Half-Open definition. So, asking if the beginning is contained returns true.
LocalDateRange.of( // `org.threeten.extra.LocalDateRange` class represents a pair of `LocalDate` objects as a date range.
LocalDate.of( 2018, 8 , 2 ) , // `java.time.LocalDate` class represents a date-only value, without time-of-day and without time zone.
LocalDate.of( 2018 , 8 , 20 )
) // Returns a `LocalDateRange` object.
.contains(
LocalDate.now() // Capture the current date as seen in the wall-clock time used by the people of the JVM’s current default time zone.
)
true
java.time
FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
Date-only
Apparently you may care about the date and not the time-of-day. If so, use LocalDate class.
For managing a date range, add the ThreeTen-Extra library to your project. This gives you access to the LocalDateRange class.
That class offers several methods for comparison: abuts, contains, encloses, equals, intersection, isBefore, isAfter, isConnected, overlaps, span, and union.
LocalDateRange r =
LocalDateRange.of(
LocalDate.of( 2018, 8 , 2 ) ,
LocalDate.of( 2018 , 8 , 20 )
)
;
LocalDate target = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ; // Capture the current date as seen in the wall-clock time used by the people of a particular time zone.
boolean contains = r.contains( target ) ;
Date-time
If you care about the date and the time-of-day in a particular time zone, use ZonedDateTime class.
Start with your LocalDate, and let that class determine the first moment of the day. The day does not always start at 00:00:00 because of anomalies such as Daylight Saving Time (DST).
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ; // Or "America/New_York", etc.
ZonedDateTime zdtStart = LocalDate.of( 2018, 8 , 2 ).atStartOfDay( z ) ;
ZonedDateTime zdtStop = LocalDate.of( 2018, 8 , 20 ).atStartOfDay( z ) ;
ZonedDateTime zdtTarget = ZonedDateTime.now( z ) ;
Represent a range with the Interval from ThreeTen-Extra. This class represents a pair of Instant objects. An Instant is a moment in UTC, always in UTC. We can easily adjust from our zoned moment to UTC by simply extracting an Instant. Same moment, same point on the timeline, different wall-clock time.
Instant instantStart = zdtStart.toInstant() ;
Instant instantStop = zdtStop.toInstant() ;
Instant instantTarget = zdtTarget.toInstant() ;
Interval interval = Interval.of( instantStart , intervalStop ) ;
boolean contains = interval.contains( instantTarget ) ;
Half-Open
The best approach to defining a span-of-time is generally the Half-Open approach. This means the beginning is inclusive while the ending is exclusive.
The comparisons in the ThreeTen-Extra range classes seen above (LocalDateRange & Interval) both use Half-Open approach. So asking if the starting date or starting moment is contained in the range results in a true.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Java Calendar.add gives wrong year

My program takes the current date and then, in a loop, adds a week to that date and prints out the new date. Something like:
Calendar cal = Calendar.getInstance();
for (int i=0; i < 52; i++) {
cal.add(Calendar.DATE, 7);
// print date out
}
The add method works the way I expect it to until it reaches Dec 30, at which point the year jumps from 2012 to 2013.
so, using today's date of 4/16/2012, i tested a few different inputs:
this - cal.add(Calendar.DATE, 38*7);
yields- "date:1/7/2013"
this - cal.add(Calendar.DATE, 37*7);
yields- "date:12/31/2013"
this - cal.add(Calendar.DATE, 37*7-1);
yields- "date:12/30/2013"
this - cal.add(Calendar.DATE, 37*7-2);
yields- "date:12/29/2012"
so i notice that the year is correct up until dec 30 and dec 31, and then it corrects itself again when it gets back to january. is there a reason why it does this? does it have anything to do with 2012 being a leap year or am i misunderstanding the add method
Did you use SimpleDateFormat to print the date and use YYYY to produce the year? If so, that is where the problem lies. Because YYYY produces the week-year and not the calendar year. And as 30/12/2012 is in calendar week 1 of 2013, YYYY produces 2013. To get the calendar year, use yyyy in your SimpleDateFormat format string.
See https://bugs.openjdk.java.net/browse/JDK-8194625
tl;dr
Use modern java.time classes, never the terrible legacy classes such as Calendar.
LocalDate // Represent a date-only value with `LocalDate`, without time-of-day and without time zone.
.now( // Capture the current date.
ZoneId.systemDefault() // Specify your desired/expected time zone explicitly.
) // Returns a `LocalDate` object.
.plusWeeks( 1 ) // Add a week, producing a new `LocalDate` object with values based on the original, per the immutable objects pattern.
.toString() // Generate text representing this date value in standard ISO 8601 format of YYYY-MM-DD.
2019-01-23
java.time
The modern approach uses the java.time classes.
The Calendar and GregorianCalendar classes are terrible, badly designed with flaws. Avoid them. Now replaced specifically by the ZonedDateTime class.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
To generate text representing that date value in standard ISO 8601 format, simply call toString.
String output = today.toString() ;
Date math is easy, with various plus… & minus… methods.
LocalDate weekLater = today.plusWeeks( 1 ) ;
You can also define a span of time as a Period or Duration. Then add that.
Period p = Period.ofWeeks( 1 ) ;
LocalDate weekLater = today.plus( p ) ;
Your example
Let's test out your example dates.
LocalDate ld = LocalDate.of( 2012 , Month.APRIL , 16 ) ;
Period period38Weeks = Period.ofWeeks( 38 ) ;
Period period37Weeks = Period.ofWeeks( 37 ) ;
Period period37WeeksLess1Days = period37Weeks.minusDays( 1 ) ;
Period period37WeeksLess2Days = period37Weeks.minusDays( 2 ) ;
LocalDate later_38 = ld.plus( period38Weeks ) ;
LocalDate later_37 = ld.plus( period37Weeks ) ;
LocalDate later_37_1 = ld.plus( period37WeeksLess1Days ) ;
LocalDate later_37_2 = ld.plus( period37WeeksLess2Days ) ;
Run code live at IdeOne.com. No problems. The 38th week is in 2013, while week 37 dates are in 2012.
later_38.toString(): 2013-01-07
later_37.toString(): 2012-12-31
later_37_1.toString(): 2012-12-30
later_37_2.toString(): 2012-12-29
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
It should be:
cal.add(Calendar.DAY_OF_YEAR, 7);
Calendar.DATE is same as Calendar.DAY_OF_MONTH.

How do you do you adjust Gregorian Calendar date so that it is 24, 48 and 78 hours before using HOUR_OF_DAY

I am wanting to adjust 3 Gregorian Calendar dates in Java, with one to be 24 hours before, the other 48, hours before and last 78 hours before. I had been using Calendar.HOUR and changed this to Calendar.HOUR_OF_DAY.
Since I did this my code stopped working. I am comparing the adjusted dates with their original values using a method that uses date1.before(date2) and date1.after(date2) to get a comparisonflag
which can be 1 or 0 which I then use in my code.
I was wondering how to do the adjust the HOUR_OF_DAY in my dates to then achieve
the above.
Some code would have been nice. But if I understand the problem correctly:
From the javadoc of Calendar:
HOUR is used for the 12-hour clock. E.g., at 10:04:15.250 PM the HOUR is 10.
HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
When adding/substracting hours from a date:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -24);
cal.add(Calendar.HOUR_OF_DAY, -24);
This should have the same effect.
tl;dr
ZonedDateTime.now() // Capture the current moment as seen through the lens of wall-clock time used by the people of a certain region, a time zone. Better to pass the expected/desired time zone as an optional argument.
.minusHours( 24 ) // Do the math, get earlier moment.
Do not use Calendar
The troublesome Calendar class and related date-time classes bundled with the earliest versions of Java are now legacy, supplanted by the java.time classes.
java.time
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
Use that time zone when asking for the current moment to be captured as a ZonedDateTime object.
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Subtract your target number of hours.
ZonedDateTime zdtMinus24h = zdt.minusHours( 24 ) ;
ZonedDateTime zdtMinus48h = zdt.minusHours( 48 ) ;
ZonedDateTime zdtMinus72h = zdt.minusHours( 72 ) ;
Compare with isBefore, isAfter, and isEqual methods. Also, Comparable is implemented.
Alternatively, you can represent the number-of-hours-to-add as a Duration.
Duration d = Duration.ofHours( 24 ) ;
ZonedDateTime zdtEarlier = zdt.minus( d ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Categories