I'm trying to set HOUR_OF_DAY field and change Timezone of the GregorianCalendar date object.
GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT+10"));
System.out.println("HOUR: " + date.get(Calendar.HOUR_OF_DAY));
date.set(Calendar.HOUR_OF_DAY, 23);
//date.get(Calendar.HOUR_OF_DAY);
date.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("HOUR: " + date.get(Calendar.HOUR_OF_DAY));
Output:
HOUR: 16
HOUR: 23
For some reason value of HOUR_OF_DAY does not change after setting different timezone. But if I uncomment date.get for HOUR_OF_DAY, everything works exactly as it should
GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT+10"));
System.out.println("HOUR: " + date.get(Calendar.HOUR_OF_DAY));
date.set(Calendar.HOUR_OF_DAY, 23);
date.get(Calendar.HOUR_OF_DAY); // uncommenting this line will is changing the output
date.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("HOUR: " + date.get(Calendar.HOUR_OF_DAY));
Output:
HOUR: 16
HOUR: 13
How is this possible? Why .get method is changing object behaviour?
The GregorianCalendar class inherits its get method from Calendar, which has the following side effect:
In lenient mode, all calendar fields are normalized.
This means that the time value and all fields are recomputed when get is called on a Calendar object. This can lead to some unpredictable behavior, particularly when coupled with setTimeZone, which has some documented buggy behavior of its own.
tl;dr
OffsetDateTime.now( ZoneOffset.ofHours( 10 ) ).withHour( 23 )
Avoid legacy date-time classes
The legacy date-time classes including GregorianCalendar are a confusing. awkward, poorly-design mess. Avoid them. Now supplanted by the java.time classes. Specifically, GregorianCalendar is replaced by ZonedDateTime.
Offset-from-UTC
You apparently want a moment with an offset-from-UTC of ten hours ahead of UTC. Define your desired offset.
ZoneOffset offset = ZoneOffset.ofHours( 10 ) ;
offset.toString(): +10:00
Get the current moment as an OffsetDateTime with that offset.
OffsetDateTime odt = OffsetDateTime.now( offset ) ;
odt.toString(): 2018-02-15T16:44:44.216642+10:00
You want to override the hour to be 23.
OffsetDateTime odt23 = odt.withHour( 23 ) ;
odt23.toString(): 2018-02-15T23:44:44.216642+10:00
Time zone
I'm trying to set HOUR_OF_DAY field and change Timezone of the GregorianCalendar date object.
Nope, you are changing the offset-from-UTC, not the time zone.
Always better to use a time zone rather than a mere offset, if you know for certain the intended zone. A time zone is a history of past, present, and future changes to the offset used by the people of a certain region. With a time zone you can always determine the offset, but not vice-versa.
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( "Australia/Brisbane" ) ;
Capture the current moment in a wall-clock time seen by the people of that zone.
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Override the hour-of-day.
ZonedDateTime zdt23 = zdt.withHour( 23 ) ;
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
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.
Related
I'm simply trying to parse a string in JLabel to a date using a simpleDateFormatter(). Based On everything I've searched online, this code should work. However, I'm receiving the "cannot find symbol - method parse(java.lang.String)" error during compiliation. Any advice on how to resolve the issue would be greatly appreciated.
The JLabel in question was populated with a date from a database query using JDBC.
Additionally, I'm aware that that java.util.Date has been deprecated, but would still like to use it for this.
Code Snippet:
private Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private JLabel dateDataLabel = new JLabel("");
private void setAndParseLabel()
{
dateDataLabel.setText(formatter.format(validatePass.eventDate));
java.util.Date aDate = formatter.parse(dateDataLabel.getText());
}
tl;dr
You are ignoring crucial issue of time zone. You are unwittingly parsing the input as a value in UTC.
You are using terrible old date-time classes that were supplanted years ago. Use java.time instead.
Example code:
LocalDateTime
.parse(
"2018-01-23 13:45".replace( " " , "T" ) // Comply with standard ISO 8601 format by replacing SPACE with `T`. Standard formats are used by default in java.time when parsing/generating strings.
) // Returns a `LocalDateTime` object. This is *not* a moment, is *not* a point on the timeline.
.atZone( // Apply a time zone to determine a moment, an actual point on the timeline.
ZoneId.of( "America/Montreal" )
) // Returns a `ZonedDateTime` object.
.toInstant() // Adjust from a time zone to UTC, if need be.
java.time
The modern approach uses the java.time classes.
Your input string is almost in standard ISO 8601 format. To fully comply, replace that SPACE in the middle with a T.
String input = "2018-01-23 13:45".replace( " " , "T" ) ;
Parse as a LocalDateTime because your input has no indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
A LocalDateTime by definition does not represent a moment, is not a point on the timeline. It represents potential moments along a range of about 26-27 hours (the range of time zones around the globe).
To determine a moment, assign a time zone (ZoneId) to get a ZonedDateTime object.
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( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
If you wish to see that same moment through the wall-clock time of UTC, extract an Instant.
Instant instant = zdt.toInstant() ; // Adjust from some time zone to UTC.
Avoid java.util.Date where feasible. But if you must interoperate with old code not yet updated to java.time, you can convert back-and-forth. Call new conversion methods added to the old classes.
java.util.Date d = java.util.Date.from( instant ) ; // Going the other direction: `myJavaUtilDate.toInstant()`
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.
java.text.Format does not have method parse, so the code does not compile.
You can refer it by java.text.DateFormat:
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
There is no method parse in java.text.Format. Use java.text.DateFormat instead:
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
java.sql.Date date = java.sql.Date.valueOf("1900-01-01");
//-2209017600000
System.out.println(date.getTime());
java.sql.Timestamp timestamp = new Timestamp(date.getTime());
System.out.println(timestamp);
if directly running in unit test, the result will be 1900-01-01 00:00:00.0
if running with debug in unit test, the result will be 1970-01-01 07:30:00.0
How does it output 1900-01-01 00:00:00.0? Where is it stored?
Why not output 1970-01-01 00:00:00.0 ? becase I saw the comment of Timestamp constructor says milliseconds since January 1, 1970, 00:00:00 GMT. A negative number is the number of milliseconds before January 1, 1970, 00:00:00 GMT.
tl;dr
Avoid the terrible old date-time classes. Use java.time. Poof, all the bizarre behavior you are seeing is gone, and your question is moot.
LocalDate // A class to represent a date-only value, without time-of-day, without time zone. Replaces `java.sql.Date` which only pretends to be date-only but actually has both a time-of-day and a time zone.
.parse( "1900-01-01" ) // Standard ISO 8601 formatted strings are parsed directly by the *java.time* classes.
.atStartOfDay( // Let java.time determine the first moment of a day.
ZoneId.of( "Pacific/Auckland" )
) // Returns a `ZonedDateTime` object.
.toString() // Generates a `String` with text in standard ISO 8601 format, wisely extended by appending the name of the time zone in square brackets.
1900-01-01T00:00+11:30[Pacific/Auckland]
You are torturing yourself with these Questions about the legacy date-time classes. Sun, Oracle, and the JCP community all gave up on those classes years ago when adopting JSR 310. I suggest you do the same.
Never use java.sql.Date
This class is part of the terrible old date-time classes that were supplanted years ago by java.time classes. This java.sql.Date in particular is especially badly designed. It extends java.util.Date while the documentation tells us to ignore the fact of that inheritance. As a subclass, it pretends to be a date-only value but actually has a time-of-day inherited from the other Date, which in turn is misnamed having both a date and a time-of-day. In addition, a time zone lurks deep within these classes, though inaccessible without any getter or setter method. Confusing? Yes, an awful mess. Never use java.sql.Date.
Instead, use java.time.LocalDate.
LocalDate ld = LocalDate.parse( "1900-01-01" ) ;
ld.toString(): 1900-01-01
Never use java.sql.Timestamp
As with java.sql.Date, the java.sql.Timestamp class was replaced years ago. Use java.time.Instant. If handed a Timestamp, immediately convert using the new conversion methods added to the old classes.
If you want the first moment of the day for a particular date, let LocalDate determine that. The first moment is not always 00:00:00, so never assume that. Specify the time zone of the region whose people use the particular wall-clock time you care about.
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( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
To see the same moment in UTC, extract 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() ;
If you wanted the first moment of the day in UTC, use OffsetDateTime.
OffsetDateTime odt = ld.atOffset( ZoneOffset.UTC ) ;
Conversion
If you must interoperate with old code not yet updated to java.time classes, you can convert back-and-forth. Call new methods added to the old classes.
java.sql.Timestamp ts = Timestamp.from( instant ) ;
…and…
Instant instant = ts.toInstant() ;
Ditto for date.
java.sql.Date d = java.sql.Date.valueOf( ld ) ;
…and…
LocalDate ld = d.toLocalDate() ;
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.
I am in MST and I want my Date in PST. I set the timeZone that I want.
Now if i do c.getTime() I always get my server time.
Instead I want Pacific Date time. Please help
How to get the date time Object in the specified timezone.
Calendar c= Calendar.getInstance();
TimeZone timezone= TimeZone.getTimeZone("PST");
c.setTimeZone(timezone)
Or, use JodaTime
#Grab( 'joda-time:joda-time:2.3' )
import org.joda.time.*
def now = new DateTime()
println now.withZone( DateTimeZone.forTimeZone( TimeZone.getTimeZone( "PST" ) ) )
TimeZone.setDefault(TimeZone.getTimeZone('PST'))
println new Date() //PST time
You can set the default timezone to PST/MST according to your need and then get the date. I would do this in a test method, if possible.
UPDATE: The Joda-Time project has been succeeded by the java.time classes. See this other Answer.
(a) Use Joda-Time (or new JSR 310 built into Java 8). Don't even think about using the notoriously bad java.util.Date/Calendar.
(b) Your question is not clear. Your comments on answers talk about comparing, but you say nothing about comparing in your question.
(c) Avoid the use of 3-letter time zone abbreviations. Read note of deprecation in Joda-Time doc for TimeZone class.
(d) Avoid default time zone. Say what you mean. The time zone of your computer can change intentionally or not.
(e) Search StackOverflow for 'joda' for lots of code snippets and examples.
(f) Here's some Joda-Time example code to get you started.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// Specify your time zone rather than rely on default.
org.joda.time.DateTimeZone californiaTimeZone = org.joda.time.DateTimeZone.forID( "America/Los_Angeles" );
org.joda.time.DateTimeZone denverTimeZone = org.joda.time.DateTimeZone.forID( "America/Denver" );
org.joda.time.DateTime nowDenver = new org.joda.time.DateTime( denverTimeZone );
org.joda.time.DateTime nowCalifornia = nowDenver.toDateTime( californiaTimeZone );
// Same moment in the Universe’s timeline, but presented in the local context.
System.out.println( "nowDenver: " + nowDenver );
System.out.println( "nowCalifornia: " + nowCalifornia );
When run…
nowDenver: 2013-11-21T18:12:49.372-07:00
nowCalifornia: 2013-11-21T17:12:49.372-08:00
About Joda-Time…
// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/
// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310
// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601
// About Daylight Saving Time (DST): https://en.wikipedia.org/wiki/Daylight_saving_time
// Time Zone list: http://joda-time.sourceforge.net/timezones.html
tl;dr
ZonedDateTime
.now(
ZoneId.of( "America/Los_Angeles" )
)
See this code run live at IdeOne.com. (Be aware the system clock on that site seems to be about a half-hour slow today.)
zdt.toString(): 2019-07-27T12:29:42.029531-07:00[America/Los_Angeles]
java.time
The modern approach uses the java.time classes built into Java 8 and later, defined in JSR 310.
I am in MST and I want my Date in PST. I set the timeZone that I want.
Never depend on the current default time zone of the JVM at runtime. As a programmer, you have no control over that default. So the results of your code may vary unexpectedly.
Always specify the optional time zone arguments to date-time methods.
Now if i do c.getTime() I always get my server time.
Learn to think not of client-time or server-time, but rather UTC. Most of your business logic, data storage, data exchange, and logging should be done in UTC. Think of UTC as the One True Time™, and all other offsets/zones are but mere variations.
For UTC, use Instant.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
Generate text representing that moment in standard ISO 8601 format.
String output = instant.toString() ;
Instead I want Pacific Date time. Please help How to get the date time Object in the specified timezone.
None of your terms (Pacific, MST, or PST) are true time zones.
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" ) ;
To adjust from UTC to a time zone, apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Edmonton" ) ; // https://time.is/Edmonton
ZonedDateTime zdt = instant.atZone( z ) ;
And try one of the time zones on the west coast of North America.
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ; // https://time.is/Los_Angeles
ZonedDateTime zdt = instant.atZone( z ) ;
To generate strings in formats other than ISO 8601, use the DateTimeFormatter class. Search Stack Overflow as this has been covered many many times already.
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.
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.
The Java Date object do not have a timezone -- it just represents a point in time.
If you would like to format a date into a timezone, you can set it in the DateFormat class. For example:
Date date = new Date ();
DateFormat df = DateFormat.getDateTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println(df.format(date));
df.setTimeZone(TimeZone.getTimeZone("EST"));
System.out.println(df.format(date));
will display a time in PST, then a time in EST.
I had to a similar issue myself recently, and setting the timezone to a locale worked better for me (i.e. not EST/EDT, but America/New_York). I tried EST then tried to do the daylight savings time offset stuff for EDT and this turned out to be a heck of lot easier. Set your timezone to whatever you want it to be then make use of the Date object to create a new date and it will for that timezone. Then you can use the format method to take a timestamp however you please.
TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
Date date = new Date();
timeStamp = date.format('yyyy-MM-dd HH:mm:ss.SSSZ');
System.out.println(timeStamp);
Returns
"2019-07-25 17:09:23:626-0400"
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.
My program is about generating (producing) a Kurosawa and making the customers produce it.
Every time we generate a Kurosawa, we have to print its id, its production date and expiration date, which is 3 months from the production date.
My problem is: How can I calculate the date after 3 months?
Use the built-in Java Calendar API.
Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 3);
Refer to the API for exactly how to print out the date, in the format you are looking for.
You could also use the much more powerful and easier to use Joda Time Library:
DateMidnight productionDate = new DateMidnight();
DateMidnight expirationDate = productionDate.plusMonths(3);
System.out.println(expirationDate.toString("dd.MM.yyyy"));
Joda Time has many advantages over the built-in Java Calendar API.
tl;dr
LocalDate.now() // Determine today’s date.
.plusMonths( 3 ) // Add three months.
java.time
The modern approach uses java.time classes.
The LocalDate class represents a date-only value without time-of-day and without time zone.
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" );
LocalDate today = LocalDate.now( z );
Add three months, letting java.time do the math.
LocalDate threeMonthsLater = today.plusMonths( 3 ) ;
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.
I believe that the Java Calendar Library should help you.
If you need to work with date arithmetic JODA works better, as Calendar likes timestamps.
/The java class Calendar is abstract. So you need to use the GregorianCalendar class./
java.util.GregorianCalendar gC = new java.util.GregorianCalendar();
java.util.Date yourDate = new java.util.Date();
gC.setTime(yourDate);
/Add 3 months/
gC.add(java.util.Calendar.MONTH_OF_YEAR, 3);
/to go back 1 week/
gC.add(java.util.Calendar.WEEK_OF_YEAR, -1);