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);
Related
My variable in java of type ZonedDateTime is say time="2017-01-03T00:00Z[UTZ]" . And when i try to get Date from like this - Date.from(time.toInstance()) it returns previous day i.e Mon Jan 02 19:00:00 EST 2017, I dont know why ? Could anyone shed some light on my it returns previous day ?
Avoid legacy date-time classes
Never use java.util.Date class. That terrible class, along with Calendar & SimpleDateFormat and others are now legacy. The new to/from conversion methods added to the old classes are intended only for use when you are interoperating with old code not yet updated to java.time. Avoid Date whenever possible.
Among the many flaws in Date is its unfortunate behavior of dynamically applying the JVM’s current default time zone while generating the text in its toString method. So it appears a Date has a time zone while actually a Date represents a moment in UTC. In other words, Date::toString lies. One of many reasons to avoid this class.
➥ In the winter of 2017, many of the time zones on the east coast of North America are five hours behind UTC. So midnight in UTC is simultaneously 7 PM (19:00) in New York, Montréal, etc. Same moment, different wall-clock time.
java.time
The Date class was supplanted by Instant years ago.
ZonedDateTime is say time="2017-01-03T00:00Z[UTZ]"
If you are trying to track moments in UTC, use either:
InstantInstant.now()
OffsetDateTime object set to UTC.OffsetDateTime.now( ZoneOffset.UTC )
Use the ZonedDateTime class when you have a moment in the context of a time zone. A time zone is a history of the past, present, and future changes to the offset-from-UTC used by the people of a particular region.
ZonedDateTime.now(
ZoneId.of( "Africa/Tunis" )
)
You can adjust between UTC and a zone. Same moment, different ways to view it, different wall-clock times.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;
…and…
Instant instant = zdt.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.
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.
ZonedDateTime.toInstant() adjusts a moment from a time zone to UTC. You end up with the same moment, different wall-clock time, and possibly a different date for the same simultaneous point on the timeline. What you are seeing is not a problem, not a discrepancy.
Classes like LocalDate and ZonedDateTime provide a human view on time.
However, often we need to work with time viewed from a machine perspective.
For this, we can use the Instant class which represents timestamps.
An Instant counts the time beginning from the first second of January 1, 1970 (1970-01-01 00:00:00) also called the EPOCH.
Instant values can be negative if they occurred before the epoch. They followISO 8601 the standard for representing date and time.
Also, use the Java Time API libraries introduced in Java 8 as there were many issues in the existing Date and Calendar APIs Please
refer: https://www.baeldung.com/java-8-date-time-intro
I have one date and i have to check whether it was saturday or sunday. Am i proceeding right way ??
Calendar gcal = new GregorianCalendar();
DateFormat dateFormat = new SimpleDateFormat("EEEE");
Date currentDate = gcal.getTime();
String strDate = dateFormat.format(currentDate);
if (!"Saturday".equals(strDate)) {
}
its working fine. but i cant compare two string like,
if (!"Saturday" || "Sunday".equals(strDate)) {}
If a date was Saturday or sunday i have to skip the loop....
Thanks in advance...
No need to create/format a Date object, use Calendar methods:
Calendar gcal = new GregorianCalendar();
if (gcal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && gcal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
}
If a date was Saturday or sunday i have to skip the loop.
Then it should be
if (!("Saturday".equals(strDate) || "Sunday".equals(strDate)) {
}
tl;dr
Is today a Saturday?
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.getDayOfWeek()
.equals( DayOfWeek.SATURDAY )
Details
Am i proceeding right way ??
No. You are using the troublesome old date-time classes that have been supplanted by the java.time classes.
Another problem is relying implicitly on default time zone. Better to specify your intended time zone explicitly. Time zone determines the date, and date determines the day-of-week, so time zone is crucial.
And another problem is that you are needlessly converting from a Calendar to a Date. But better to avoid these classes entirely.
DayOfWeek
The DayOfWeek enum defines seven objects, one for each day of the week.
You should be passing these objects around your code rather than a string. Notice in the code below that we do not use strings at all.
Be clear that these DayOfWeek objects are not strings. They are real objects, offering several methods. Those methods include toString that generates a hard-coded String in English, all in uppercase. The method getDisplayName generates the name of the day-of-week automatically localized in various human languages.
Enums in Java are much more powerful and practical than conventionally seen in other languages. See Oracle Tutorial.
LocalDate
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.
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 );
today.toString(): 2017-02-27
Interrogate the LocalDate object for its DayOfWeek.
DayOfWeek dow = today.getDayOfWeek();
dow.toString(): MONDAY
Compare to your target day-of-week.
Boolean isTodaySaturday = dow.equals( DayOfWeek.SATURDAY );
isTodaySaturday.toString(): false
Try this code live at IdeOne.com.
See similar Question: How to skip weekends while adding days to LocalDate in Java 8?
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 and 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 SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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.
Alternatively:
if (!strDate.matches("Saturday|Sunday")) {
}
But it is slower.
This question already has answers here:
Today is nth day of year [duplicate]
(6 answers)
Closed 5 years ago.
Say you have a Date object with day, month and year values.
I want to know which date it is.
By this I mean, like 5th of March is for example the 65th of the year.
Or like 15th of January is the 15th.
Please no joda time. ( Not used in the current project. )
You can use the Calendar which java provides. Using the get() method and DAY_OF_YEAR you can get what you want.
Ex:-
Calendar cal = new GregorianCalendar();
cal.setTime(new Date()); // Give your own date
System.out.println(cal.get(Calendar.DAY_OF_YEAR));
Calendar#get(Calendar.DAY_OF_YEAR);
tl;dr
LocalDate.now( ZoneId.of( "America/Montreal" ) ) // Today's date in a particular time zone.
.getDayOfYear() // Returns day-of-year (1-366).
Details
The other Answers with Calendar class are outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.
Using java.time
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.
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 );
2017-01-23
We can ask what day-of-year that is, 1-366.
int dayOfYear = today.getDayOfYear() ;
23
We can adjust that LocalDate into a specific day-of-year.
LocalDate ld = today.withDayOfYear( 187 ) ;
2017-07-06
See this code run live at IdeOne.com.
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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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 try to format a time interval using SimpleDateFormat.
import java.text.*;
import java.util.*;
public class DateFormatTest {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
long interval = 1000;
System.out.println("Interval in millis: " + interval);
System.out.println("Expected result: 00:00:01");
System.out.println("Result using Date and SimpleDateFormat: " +
sdf.format(new Date(interval)));
}
}
I get the following result:
Interval in millis: 1000
Expected result: 00:00:01
Result using Date and SimpleDateFormat: 01:00:01
I am in GMT+1 time zone. But it should not be reflected in the result.
Of course it can be solved with System.out.printf, but what I am searching is the reason.
I am in GMT+1 time zone. But should not be reflected in the result.
What makes you think so? new Date(0) is at 00:00AM GMT on Jan 1st 1970. So it is at 01:00AM if your default timezone is GMT + 1.
I am in GMT+1 time zone. But it should not be reflected in the result.
Then you should set the time zone in the SimpleDateFormat. SimpleDateFormat is doing exactly the right thing - it's formatting the instant in time (just after midnight UTC 1970) in the time zone it's working in.
To change the time zone, just use:
sdf.setTimeZone(TimeZone.getTimeZone("etc/UTC"));
It's not clear whether you should really be using SimpleDateFormat at all, though. You're not trying to format a date/time - you're trying to format an interval, given your variable name.
I suggest you use Joda Time which has a much richer type system, and will allow you to express what you really want.
Also, if you really want to use SimpleDateFormat, you probably want to use HH instead of hh in your format string. (hh is a 12-hour value, 1-12. You want 00:00:01, not 12:00:01.) hh is rarely appropriate when you don't also have an am/pm designator in your pattern.
Wrong data type
You are using the wrong class. You are trying to represent a duration of milliseconds and a time-of-day. Neither fits the Date class. That class represents a moment (a date, with time-of-day, in context of UTC).
Also, java.util.Date is a terrible class, designed by people who did not understand date-time handling. Now obsolete.
java.time
The modern solution uses java.time classes.
LocalTime
Specifically, LocalTime for a time-of-day using a generic 24-hour day, without a date, and without the context of a time zone or offset-from-UTC.
The start of a day for generic days is 00:00:00. We have a constant for that: LocalTime.MIN. But know that in various time zones, on various dates, the day may start at another time such as 01:00:00.
LocalTime lt = LocalTime.of( 15 , 30 ) ; // 3:30 PM.
Duration
To represent a span-of-time unattached to the timeline, on a scale of hours-minutes-seconds, use Duration class.
Duration d = Duration.ofMilliseconds( 1_000 ) ;
We can do math with date-time objects.
LocalTime lt = LocalTime.MIN.plus( d ) ;
You should know that java.time classes use a resolution of nanoseconds, much finer than the milliseconds used by the legacy date-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.
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.
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.