We have a java code snippet here
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
Date date = new Date();
int days = 5;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formatter.format(date.getTime() + (days*86400000));
System.out.println(strDate);
}
}
to add n no. of days to today's date. The result will be correct upto n=24 but gives previous month' after n=24. Why it is so?
The problem is the the int is overflowing
consider
int days = 25;
int d = days*86400000;
System.out.println(d);
try
int days = 25;
long d = days*86400000L;
System.out.println(d);
tl;dr
LocalDate // Represent a date-only, without a time-of-day and without a time zone.
.now() // Capture the current date, as seen through your JVM’s current default time zone. Better to pass a `ZoneId` as the optional argument.
.plusDays( 5 ) // Add five days, returning a new `LocalDate` object. Per the Immutable Objects pattern, a new object is produced rather than changing (“mutating”) the original.
.format( // Generate text representing the date value of our `LocalDate` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) // Define a formatting pattern to suit your taste. Or call the `.ofLocalized…` methods to localize automatically.
) // Returns a `String`.
java.time
Date class represents a moment in UTC, a date with a time-of-day, and an offset-from-UTC of zero. Wrong class to use when working with date-only values.
Avoid using the terrible old legacy date-time classes such as Calendar, Date, and SimpleDateFormat. These classes were supplanted years ago by the java.time classes.
Do not track days as a count of seconds or milliseconds. Days are not always 24 hours long, and years are not always 365 days long.
LocalDate
Instead, use LocalDate class.
LocalDate today = LocalDate.now() ;
LocalDate later = today.plusDays( 5 ) ;
Convert
Best to avoid the legacy classes altogether. But 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.
For Date you need to add a time-of-day. I expect you will want to go with the first moment of the day. And I'll assume you want to frame the date as UTC rather than a time zone. We must go through a OffsetDateTime object to add the time-of-day and offset. For the offset, we use the constant ZoneOffset.UTC. Then we extract the more basic Instant class object to convert to a java.util.Date.
OffsetDateTime odt = OffsetDateTime.of( later , LocalTime.MIN , ZoneOffset.UTC ) ; // Combine the date with time-of-day and with an offset-from-UTC.
Instant instant = odt.toInstant() ; // Convert to the more basic `Instant` class, a moment in UTC, always UTC by definition.
java.util.Date d = java.util.Date.from( instant ) ; // Convert from modern class to legacy class.
Going the other direction:
Instant instant = d.toInstant() ; // Convert from legacy class to modern class.
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.
Use days*86400000L to make this a long calculation otherwise the int value overflows.
Try this one in your code:
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, 5);
strDate = formatter.format(cal.getTime());
Related
Hi i am trying to get the current year in the below code however it is returning a 1970 year instead of 2020 last month this was working correctly but since we in January 2020, it is now returning a date from 1970, please assist
public String firstDateOfNextMonth(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar today = Calendar.getInstance();
Calendar next = Calendar.getInstance();
today.clear();
Date date;
next.clear();
next.set(Calendar.YEAR, today.get(Calendar.YEAR));
next.set(Calendar.MONTH, today.get(Calendar.MONTH)+ 1);
next.set(Calendar.DAY_OF_MONTH, 1);
date = next.getTime();
Log.d(TAG, "The Date: " + dateFormat.format(date));
return dateFormat.format(date);
}
If you have Java 8 or above, then you have java.time and you won't have to rely on outdated datetime implementations and you can do it this way:
public static String getFirstOfNextMonth() {
// get a reference to today
LocalDate today = LocalDate.now();
// having today,
LocalDate firstOfNextMonth = today
// add one to the month
.withMonth(today.getMonthValue() + 1)
// and take the first day of that month
.withDayOfMonth(1);
// then return it as formatted String
return firstOfNextMonth.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
which prints the following when called today (2020-01-03) like System.out.println(getFirstOfNextMonth());:
2020-02-01
You might have to involve an external library, the ThreeTenAbp if you want it to work in Android below API level 26. Its use is explained in this question.
not sure why the today date gets cleared, remove today.clear() at line 4
today.clear(); initalize all elements of a date with the value 0
removing this line will give you the right answer
tl;dr
LocalDate // Represent a date-only value without a time-of-day and without a time zone.
.now( // Determine the current date as seen through the wall-clock time used by people in certain region (a time zone).
ZoneId.of( "America/Montreal" ) // Real time zone names have names in the format of `Continent/Region`. Never use 2-4 letter pseudo-zones such as `IST`, `PST`, or `CST`, which are neither standardized nor unique.
) // Return a `LocalDate`.
.with( // Move from one date another by passing a `TemporalAdjuster` implementation.
TemporalAdjusters // Class providing several implementations of `TemporalAdjuster`.
.firstDayOfNextMonth() // This adjuster finds the date of the first of next month, as its name suggests.
) // Returns another `LocalDate` object. The original `LocalDate` object is unaltered.
.toString() // Generate text in standard ISO 8601 format of YYYY-MM-DD.
See this code run live at IdeOne.com.
2020-02-01
Details
You are using terrible date-time classes that were made obsolete years ago by the unanimous adoption of JSR 310 defining the java.time classes.
The Answer by deHaar is correct. Here is an even shorter solution.
TemporalAdjuster
To move from one date to another, the java.time classes include the TemporalAdjuster interface. Pass one of these objects to the with method found on many of the other java.time classes.
TemporalAdjusters.firstDayOfNextMonth()
Several implementations of that interface are found in the class TemporalAdjusters (note the s plural). One of those is firstDayOfNextMonth(), just what you need.
Get today's date. A time zone is required, as for any given moment the date varies around the globe by time zone. If omitted, your JVM's current default time zone is implicitly applied. Better to be explicit.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate today = LocalDate.now( z ) ;
Get your TemporalAdjuster object.
TemporalAdjuster ta = TemporalAdjusters.firstDayOfNextMonth() ;
Apply that adjuster to get another LocalDate object. Note that java.time classes are immutable by design. So we get a new object rather than altering the original.
LocalDate firstOfNextMonth = today.with( ta ) ;
We can shorten this code to a one-liner, if desired.
LocalDate firstOfNextMonth =
LocalDate
.now(
ZoneId.of( "Africa/Tunis" )
)
.with(
TemporalAdjusters.firstDayOfNextMonth()
)
;
Text
Your desired output format of YYYY-MM-DD complies with the ISO 8601 standard used by default in the java.time classes when parsing/generating text. So no formatting pattern need be specified.
String output = firstOfNextMonth.toString() ;
2020-02-01
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.
You are using Calendar.clear() which clears all the fields of your calendar, and essentially reverts it to 1/1/1970 (epoch time 0).
remove today.clear() and you'll get the correct answer
see more here
Remove next.clear();. As Calendar next= Calendar.getInstance(); initiates next with the current date, in your cases Fri Jan 03 2020 15:07:53. And when you do next.clear(), it sets to the inital epoch.
Epoch, also known as Unix timestamps, is the number of seconds (not
milliseconds!) that have elapsed since January 1, 1970 at 00:00:00 GMT
(1970-01-01 00:00:00 GMT).
Hello I'm trying to convert a string in the format "17:50" to a date in android but when I try to run this code I get the correct hour from the string but the full date is from 1970. I need this date to schedule some local notifications on a given time of the day or in the next day.
String dtStart = "17:50";
SimpleDateFormat format = new SimpleDateFormat("H:mm");
try {
Calendar cal = Calendar.getInstance();
Date date = format.parse(dtStart);
cal.setTime(date);
System.out.println(cal.getTime());
} catch (ParseException e) {
e.printStackTrace();
}
Thu Jan 01 17:50:00 BRT 1970
It's not an error, your code works well. Just if you want to get current date, you have to add the difference between current day and 1st of January 1970.
Your parsed date gives you 17:30 hours, which means 17 * 60 * 60 * 1000 ms + 30 * 60 + 1000 ms.
This way you can find current day: https://stackoverflow.com/a/1908419/4142087
What Anton suggested was correct, and the current day / next day logic is your custom implementation. You have to check current time and if it past that time, jump to setting up the alarm the next day.
java.time
You need a time-of-day class to represent your intended meaning. The legacy date-time classes from the earliest versions of Java lack such a class. The java.sql.Time class pretends to do this, but actually contains a date as well due to poor design decisions.
LocalTime
You want the LocalTime class for a time-of-day value without a date and without a time zone.
It uses a generic 24-hour single-day clock. Adding/subtracting spans of time wraps around the clock since it lacks any concept of dates.
Define a formatting pattern to match your input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "H:mm" ) ; // Uppercase `H` means 24-hour clock, lowercase `h` means 12-hour clock.
Parse input string.
String input = "7:50" ;
LocalTime lt = LocalTime.parse( input , f ) ;
Generate a string in standard ISO 8601 format.
String output = lt.toString() ;
07:50
Perhaps your business logic requires assigning the time-of-day to a date. To determine a moment, a point on the timeline, you must also specify a time zone.
LocalDate ld = LocalDate.of( 2018 , Month.MARCH , 27 ) ;
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
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, 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.
I have this code:
public static String formatMinSecOrHourMinSec(final String length) {
try {
final SimpleDateFormat hhmmss = new SimpleDateFormat("HH:mm:ss", Locale.GERMAN);
final Date date = hhmmss.parse(length);
final GregorianCalendar gc0 = new GregorianCalendar(Locale.GERMAN);
gc0.setTime(date);
if(gc0.getTimeInMillis() >= 3600 * 1000){
return hhmmss.format(gc0.getTime());
}else{
final SimpleDateFormat mmss = new SimpleDateFormat("mm:ss");
return mmss.format(gc0.getTime());
}
} catch (final ParseException e) {
LOGGER.debug("Konnte die Länge nicht parsen: " + length + "\n" + e);
return length;
}
}
I estimate that it returns 01:29:00 if length is set to 01:29:00 but it returns 29:00. This is because gc0.getTimeInMillis() returns one hour less (3600 * 1000) than expected. What am I doing wrong ?
this is because java.util.Date is using your default time zone. (print time in ms from date and you will see).
To fix it try:
final SimpleDateFormat hhmmss = new SimpleDateFormat("HH:mm:ss");
hhmmss.setTimeZone(TimeZone.getTimeZone("UTC"));
tl;dr
Do not conflate a span-of-time with a time-of-day. Two different concepts deserve two different classes. A span-of-time is represented by the Duration (or Period) class.
Duration
.ofHours( 1 )
.plusMinutes( 29 )
…or…
Duration
.parse( "PT1H29M" )
Wrong classes
First, you are using inappropriate classes. Apparently you are trying to track a span-of-time but are using time-of-day to do so. A span and a time are two different concepts. Mixing the two leads to ambiguity, confusion, and errors.
Second, you are using terrible old classes that were supplanted years ago by the java.time classes. Never use SimpleDateFormat, GregorianCalendar, etc.
Span-of-time
The correct class for a span-of-time in the range of hours-minutes-seconds is Duration. For a range of years-months-days, use Period.
You can instantiate your Duration from numbers of hours and minutes.
Duration d = Duration.ofHours( 1 ).plusMinutes( 29 ) ;
Or you can parse a string in standard ISO 8601 format, PnYnMnDTnHnMnS.
Duration d = Duration.parse( "PT1H29M" ) ;
Date-Time math
You can do math with date-time values. Perhaps you want to know when is an hour and twenty-nine minutes from now.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ; // Capture the current moment as seen though the wall-clock time used by the people of some particular region.
ZonedDateTime later = now.plus( d ) ; // Add a span-of-time to determine a later moment (or an earlier moment if the `Duration` is negative).
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 have created new SimpleDateFormat object which parses the given string as date object. The date format is as below:
SimpleDateFormat simpledateFormat = new SimpleDateFormat("dd-MM-yyyy");
And I am setting this date to calendar instance as below:
Date date = sampledateFormat.parse("01-08-2013");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Now I am getting the day of the day of the week from this calendar. It is giving wrong value.
System.out.println(calendar.DAY_OF_WEEK);
The output it is giving is 7 i.e. Saturday but the expected value is 5 i.e. Thursday. Whats the problem?
You should print
calendar.get(Calendar.DAY_OF_WEEK);
The Calendar class has DAY_OF_WEEK as integer constant (with value 7) which should be used in conjunction with the Calendar.get(int) method. DAY_OF_WEEK is a calendar field, and all these constant fields are used to get() different values from the calendar instance. Their value is irrelevant.
tl;dr
LocalDate.parse( // Parse the input string by specified formatting pattern to get a date-only `LocalDate` object.
"01-08-2013" ,
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
.getDayOfWeek() // Get a `DayOfWeek` enum object. This is *not* a mere String.
.getValue() // Ask the `DayOfWeek` object for its number, 1-7 for Monday-Sunday per ISO 8601 standard.
4
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes such as SimpleDateFormat and Date and Calendar.
The LocalDate class represents a date-only value without time-of-day and without time zone.
Define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
Parse the input string.
LocalDate ld = LocalDate.parse( "01-08-2013" , f ) ;
ld.toString(): 2013-08-01
Interrogate for the day-of-week. Get a DayOfWeek enum object, one of seven pre-defined objects, for Monday-Sunday.
DayOfWeek dow = ld.getDayOfWeek() ;
dow.toString(): THURSDAY
You can ask that DayOfWeek object for a localized name and for a number 1-7 for Monday-Sunday per the ISO 8601 standard.
int dowNumber = dow.getValue() ;
4
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; // Or Locale.US, Locale.ITALY, etc.
jeudi
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, 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 class has 2 properties that make up its date:
java.util.Date date;
String timeZone;
How can I see if this date is before the current time on the server?
Basically I want to write something like this, but take timeZone into account:
return date.before(new Date());
Date stores internally as UTC, so your timeZone variable is not necessary. You can simply use Date.before(Date).
Calendar startCalendar = Calendar.getInstance();
int startTimeZoneOffset = TimeZone.getTimeZone(timeZone).getOffset(startDate.getTime()) / 1000 / 60;
startCalendar.setTime(startDate);
startCalendar.add(Calendar.MINUTE, startTimeZoneOffset);
Calendar nowCalendar = Calendar.getInstance();
int nowTimeZoneOffset = nowCalendar.getTimeZone().getOffset(new Date().getTime()) / 1000 / 60;
nowCalendar.setTime(new Date());
nowCalendar.add(Calendar.MINUTE, nowTimeZoneOffset);
return startCalendar.before(nowCalendar);
tl;dr
Use Instant class, which is always in UTC. So time zone becomes a non-issue.
someInstant.isBefore( Instant.now() )
java.time
The modern approach uses the java.time classes that supplanted the terrible Date & Calendar classes.
As the correct Answer by Kuo stated, your java.util.Date is recording a moment in UTC. So no need for a time zone.
Likewise, its replacement, the java.time.Instant class, also records a moment in UTC. So no time zone needed.
Instant instant = Instant.now() ; // Capture current in UTC.
So all you need as member variables on your class is Instant.
public class Event {
Instant when ;
…
}
To compare Instant objects, use the isAfter, isBefore, and equals methods.
someInstant.isBefore( Instant.now() )
For presentation in a time zone expected by the user, assign a ZoneId to get a ZonedDateTime object. The Instant and the ZonedDateTime both represent the same moment, the same point on the timeline, but viewed through different wall-clock time.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same moment, different wall-clock time.
String output = zdt.toString() ; // Generate text in standard ISO 8601 format, wisely extended to append the name of the zone in square brackets.
Or let java.time automatically localize output. To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.JAPAN, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( l );
String output = zdt.format( f );
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.