How to add one day to a date? [duplicate] - java

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 4 years ago.
I want to add one day to a particular date. How can I do that?
Date dt = new Date();
Now I want to add one day to this date.

Given a Date dt you have several possibilities:
Solution 1: You can use the Calendar class for that:
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
Solution 2: You should seriously consider using the Joda-Time library, because of the various shortcomings of the Date class. With Joda-Time you can do the following:
Date dt = new Date();
DateTime dtOrg = new DateTime(dt);
DateTime dtPlusOne = dtOrg.plusDays(1);
Solution 3: With Java 8 you can also use the new JSR 310 API (which is inspired by Joda-Time):
Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);

Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));
Date has a constructor using the milliseconds since the UNIX-epoch. the getTime()-method gives you that value. So adding the milliseconds for a day, does the trick. If you want to do such manipulations regularly I recommend to define constants for the values.
Important hint: That is not correct in all cases. Read the WARNING comment, below.

I found a simple method to add arbitrary time to a Date object
Date d = new Date(new Date().getTime() + 86400000)
Where:
86 400 000 ms = 1 Day : 24*60*60*1000
3 600 000 ms = 1 Hour : 60*60*1000

As mentioned in the Top answer, since java 8 it is possible to do:
Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);
but this can sometimes lead to an DateTimeException like this:
java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 2014-11-29T03:20:10.800Z of type java.time.Instant
It is possible to avoid this Exception by simply passing the time zone:
LocalDateTime.from(dt.toInstant().atZone(ZoneId.of("UTC"))).plusDays(1);

tl;dr
LocalDate.of( 2017 , Month.JANUARY , 23 )
.plusDays( 1 )
java.time
Best to avoid the java.util.Date class altogether. But if you must do so, you can convert between the troublesome old legacy date-time classes and the modern java.time classes. Look to new methods added to the old classes.
Instant
The Instant class, is close to being equivalent to Date, both being a moment on the timeline. Instant resolves to nanoseconds, while Date is milliseconds.
Instant instant = myUtilDate.toInstant() ;
You could add a day to this, but keep in mind this in UTC. So you will not be accounting for anomalies such as Daylight Saving Time. Specify the unit of time with the ChronoUnit class.
Instant nextDay = instant.plus( 1 , ChronoUnit.DAYS ) ;
ZonedDateTime
If you want to be savvy with time zones, specify a ZoneId to get a ZonedDateTime. 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 = instant.atZone( z ) ;
ZonedDateTime zdtNextDay = zdt.plusDays( 1 ) ;
You can also represent your span-of-time to be added, the one day, as a Period.
Period p = Period.ofDays( 1 ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ).plus( p ) ;
You may want the first moment of that next day. Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time, such as 01:00:00. Let java.time determine the first moment of the day on that date in that zone.
LocalDate today = LocalDate.now( z ) ;
LocalDate tomorrow = today.plus( p ) ;
ZonedDateTime zdt = tomorrow.atStartOfDay( 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, 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.
Update: The Joda-Time library is now in maintenance mode. The team advises migration to the java.time classes. I am leaving this section intact for history.
Joda-Time
The Joda-Time 2.3 library makes this kind of date-time work much easier. The java.util.Date class bundled with Java is notoriously troublesome, and should be avoided.
Here is some example code.
Your java.util.Date is converted to a Joda-Time DateTime object. Unlike a j.u.Date, a DateTime truly knows its assigned time zone. Time zone is crucial as adding a day to get the same wall-clock time tomorrow might mean making adjustments such as for a 23-hour or 25-hour day in the case of Daylight Saving Time (DST) here in the United States. If you specify the time zone, Joda-Time can make that kind of adjustment. After adding a day, we convert the DateTime object back into a java.util.Date object.
java.util.Date yourDate = new java.util.Date();
// Generally better to specify your time zone rather than rely on default.
org.joda.time.DateTimeZone timeZone = org.joda.time.DateTimeZone.forID( "America/Los_Angeles" );
DateTime now = new DateTime( yourDate, timeZone );
DateTime tomorrow = now.plusDays( 1 );
java.util.Date tomorrowAsJUDate = tomorrow.toDate();
Dump to console…
System.out.println( "yourDate: " + yourDate );
System.out.println( "now: " + now );
System.out.println( "tomorrow: " + tomorrow );
System.out.println( "tomorrowAsJUDate: " + tomorrowAsJUDate );
When run…
yourDate: Thu Apr 10 22:57:21 PDT 2014
now: 2014-04-10T22:57:21.535-07:00
tomorrow: 2014-04-11T22:57:21.535-07:00
tomorrowAsJUDate: Fri Apr 11 22:57:21 PDT 2014

you can use this method after import org.apache.commons.lang.time.DateUtils:
DateUtils.addDays(new Date(), 1);

This will increase any date by exactly one
String untildate="2011-10-08";//can take any date in current format
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse(untildate));
cal.add( Calendar.DATE, 1 );
String convertedDate=dateFormat.format(cal.getTime());
System.out.println("Date increase by one.."+convertedDate);

Java 8 Time API:
Instant now = Instant.now(); //current date
Instant after= now.plus(Duration.ofDays(300));
Date dateAfter = Date.from(after);

use DateTime object obj.Add to add what ever you want day hour and etc.
Hope this works:)

I prefer joda for date and time arithmetics because it is much better readable:
Date tomorrow = now().plusDays(1).toDate();
Or
endOfDay(now().plus(days(1))).toDate()
startOfDay(now().plus(days(1))).toDate()

Java 8 LocalDate API
LocalDate.now().plusDays(1L);

To make it a touch less java specific, the basic principle would be to convert to some linear date format, julian days, modified julian days, seconds since some epoch, etc, add your day, and convert back.
The reason for doing this is that you farm out the "get the leap day, leap second, etc right' problem to someone who has, with some luck, not mucked this problem up.
I will caution you that getting these conversion routines right can be difficult. There are an amazing number of different ways that people mess up time, the most recent high profile example was MS's Zune. Dont' poke too much fun at MS though, it's easy to mess up. It doesn't help that there are multiple different time formats, say, TAI vs TT.

best thing to use:
long currenTime = System.currentTimeMillis();
long oneHourLater = currentTime + TimeUnit.HOURS.toMillis(1l);
Similarly, you can add MONTHS, DAYS, MINUTES etc

In very special case If you asked to do your own date class, possibly from your Computer Programming Professor; This method would do very fine job.
public void addOneDay(){
int [] months = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
day++;
if (day> months[month-1]){
month++;
day = 1;
if (month > 12){
year++;
month = 1;
}
}
}

Java 1.8 version has nice update for data time API.
Here is snippet of code:
LocalDate lastAprilDay = LocalDate.of(2014, Month.APRIL, 30);
System.out.println("last april day: " + lastAprilDay);
LocalDate firstMay = lastAprilDay.plusDays(1);
System.out.println("should be first may day: " + firstMay);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
String formatDate = formatter.format(firstMay);
System.out.println("formatted date: " + formatDate);
Output:
last april day: 2014-04-30
should be first may day: 2014-05-01
formatted date: 01
For more info see Java documentations to this classes:
LocalDate
DateTimeFormatter

U can try java.util.Date library like this way-
int no_of_day_to_add = 1;
Date today = new Date();
Date tomorrow = new Date( today.getYear(), today.getMonth(), today.getDate() + no_of_day_to_add );
Change value of no_of_day_to_add as you want.
I have set value of no_of_day_to_add to 1 because u wanted only one day to add.
More can be found in this documentation.

you want after days find date this code try..
public Date getToDateAfterDays(Integer day) {
Date nowdate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(nowdate);
cal.add(Calendar.DATE, day);
return cal.getTime();
}

I will show you how we can do it in Java 8. Here you go:
public class DemoDate {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 1 day to the current date
LocalDate date1Day = today.plus(1, ChronoUnit.DAYS);
System.out.println("Date After 1 day : " + date1Day);
}
}
The output:
Current date: 2016-08-15
Date After 1 day : 2016-08-16

Related

How to add tomorrow date time in mongoDB using SpringBoot? [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 4 years ago.
I want to add one day to a particular date. How can I do that?
Date dt = new Date();
Now I want to add one day to this date.
Given a Date dt you have several possibilities:
Solution 1: You can use the Calendar class for that:
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
Solution 2: You should seriously consider using the Joda-Time library, because of the various shortcomings of the Date class. With Joda-Time you can do the following:
Date dt = new Date();
DateTime dtOrg = new DateTime(dt);
DateTime dtPlusOne = dtOrg.plusDays(1);
Solution 3: With Java 8 you can also use the new JSR 310 API (which is inspired by Joda-Time):
Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);
Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));
Date has a constructor using the milliseconds since the UNIX-epoch. the getTime()-method gives you that value. So adding the milliseconds for a day, does the trick. If you want to do such manipulations regularly I recommend to define constants for the values.
Important hint: That is not correct in all cases. Read the WARNING comment, below.
I found a simple method to add arbitrary time to a Date object
Date d = new Date(new Date().getTime() + 86400000)
Where:
86 400 000 ms = 1 Day : 24*60*60*1000
3 600 000 ms = 1 Hour : 60*60*1000
As mentioned in the Top answer, since java 8 it is possible to do:
Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);
but this can sometimes lead to an DateTimeException like this:
java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: 2014-11-29T03:20:10.800Z of type java.time.Instant
It is possible to avoid this Exception by simply passing the time zone:
LocalDateTime.from(dt.toInstant().atZone(ZoneId.of("UTC"))).plusDays(1);
tl;dr
LocalDate.of( 2017 , Month.JANUARY , 23 )
.plusDays( 1 )
java.time
Best to avoid the java.util.Date class altogether. But if you must do so, you can convert between the troublesome old legacy date-time classes and the modern java.time classes. Look to new methods added to the old classes.
Instant
The Instant class, is close to being equivalent to Date, both being a moment on the timeline. Instant resolves to nanoseconds, while Date is milliseconds.
Instant instant = myUtilDate.toInstant() ;
You could add a day to this, but keep in mind this in UTC. So you will not be accounting for anomalies such as Daylight Saving Time. Specify the unit of time with the ChronoUnit class.
Instant nextDay = instant.plus( 1 , ChronoUnit.DAYS ) ;
ZonedDateTime
If you want to be savvy with time zones, specify a ZoneId to get a ZonedDateTime. 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 = instant.atZone( z ) ;
ZonedDateTime zdtNextDay = zdt.plusDays( 1 ) ;
You can also represent your span-of-time to be added, the one day, as a Period.
Period p = Period.ofDays( 1 ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ).plus( p ) ;
You may want the first moment of that next day. Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time, such as 01:00:00. Let java.time determine the first moment of the day on that date in that zone.
LocalDate today = LocalDate.now( z ) ;
LocalDate tomorrow = today.plus( p ) ;
ZonedDateTime zdt = tomorrow.atStartOfDay( 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, 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.
Update: The Joda-Time library is now in maintenance mode. The team advises migration to the java.time classes. I am leaving this section intact for history.
Joda-Time
The Joda-Time 2.3 library makes this kind of date-time work much easier. The java.util.Date class bundled with Java is notoriously troublesome, and should be avoided.
Here is some example code.
Your java.util.Date is converted to a Joda-Time DateTime object. Unlike a j.u.Date, a DateTime truly knows its assigned time zone. Time zone is crucial as adding a day to get the same wall-clock time tomorrow might mean making adjustments such as for a 23-hour or 25-hour day in the case of Daylight Saving Time (DST) here in the United States. If you specify the time zone, Joda-Time can make that kind of adjustment. After adding a day, we convert the DateTime object back into a java.util.Date object.
java.util.Date yourDate = new java.util.Date();
// Generally better to specify your time zone rather than rely on default.
org.joda.time.DateTimeZone timeZone = org.joda.time.DateTimeZone.forID( "America/Los_Angeles" );
DateTime now = new DateTime( yourDate, timeZone );
DateTime tomorrow = now.plusDays( 1 );
java.util.Date tomorrowAsJUDate = tomorrow.toDate();
Dump to console…
System.out.println( "yourDate: " + yourDate );
System.out.println( "now: " + now );
System.out.println( "tomorrow: " + tomorrow );
System.out.println( "tomorrowAsJUDate: " + tomorrowAsJUDate );
When run…
yourDate: Thu Apr 10 22:57:21 PDT 2014
now: 2014-04-10T22:57:21.535-07:00
tomorrow: 2014-04-11T22:57:21.535-07:00
tomorrowAsJUDate: Fri Apr 11 22:57:21 PDT 2014
you can use this method after import org.apache.commons.lang.time.DateUtils:
DateUtils.addDays(new Date(), 1);
This will increase any date by exactly one
String untildate="2011-10-08";//can take any date in current format
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse(untildate));
cal.add( Calendar.DATE, 1 );
String convertedDate=dateFormat.format(cal.getTime());
System.out.println("Date increase by one.."+convertedDate);
Java 8 Time API:
Instant now = Instant.now(); //current date
Instant after= now.plus(Duration.ofDays(300));
Date dateAfter = Date.from(after);
use DateTime object obj.Add to add what ever you want day hour and etc.
Hope this works:)
I prefer joda for date and time arithmetics because it is much better readable:
Date tomorrow = now().plusDays(1).toDate();
Or
endOfDay(now().plus(days(1))).toDate()
startOfDay(now().plus(days(1))).toDate()
Java 8 LocalDate API
LocalDate.now().plusDays(1L);
To make it a touch less java specific, the basic principle would be to convert to some linear date format, julian days, modified julian days, seconds since some epoch, etc, add your day, and convert back.
The reason for doing this is that you farm out the "get the leap day, leap second, etc right' problem to someone who has, with some luck, not mucked this problem up.
I will caution you that getting these conversion routines right can be difficult. There are an amazing number of different ways that people mess up time, the most recent high profile example was MS's Zune. Dont' poke too much fun at MS though, it's easy to mess up. It doesn't help that there are multiple different time formats, say, TAI vs TT.
best thing to use:
long currenTime = System.currentTimeMillis();
long oneHourLater = currentTime + TimeUnit.HOURS.toMillis(1l);
Similarly, you can add MONTHS, DAYS, MINUTES etc
In very special case If you asked to do your own date class, possibly from your Computer Programming Professor; This method would do very fine job.
public void addOneDay(){
int [] months = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
day++;
if (day> months[month-1]){
month++;
day = 1;
if (month > 12){
year++;
month = 1;
}
}
}
Java 1.8 version has nice update for data time API.
Here is snippet of code:
LocalDate lastAprilDay = LocalDate.of(2014, Month.APRIL, 30);
System.out.println("last april day: " + lastAprilDay);
LocalDate firstMay = lastAprilDay.plusDays(1);
System.out.println("should be first may day: " + firstMay);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd");
String formatDate = formatter.format(firstMay);
System.out.println("formatted date: " + formatDate);
Output:
last april day: 2014-04-30
should be first may day: 2014-05-01
formatted date: 01
For more info see Java documentations to this classes:
LocalDate
DateTimeFormatter
U can try java.util.Date library like this way-
int no_of_day_to_add = 1;
Date today = new Date();
Date tomorrow = new Date( today.getYear(), today.getMonth(), today.getDate() + no_of_day_to_add );
Change value of no_of_day_to_add as you want.
I have set value of no_of_day_to_add to 1 because u wanted only one day to add.
More can be found in this documentation.
you want after days find date this code try..
public Date getToDateAfterDays(Integer day) {
Date nowdate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(nowdate);
cal.add(Calendar.DATE, day);
return cal.getTime();
}
I will show you how we can do it in Java 8. Here you go:
public class DemoDate {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 1 day to the current date
LocalDate date1Day = today.plus(1, ChronoUnit.DAYS);
System.out.println("Date After 1 day : " + date1Day);
}
}
The output:
Current date: 2016-08-15
Date After 1 day : 2016-08-16

Java Date giving different dates

I need my Java Android app to extract and compare dates, but it's all a mess to get the correct date.
TimeZone timeZone = TimeZone.getTimeZone("GMT");
Calendar calendar = Calendar.getInstance(timeZone);
Date currentTime = calendar.getTime();
Log.i(logtag, "Date currentTime="+currentTime);
String tidspunkt = calendar.get(Calendar.YEAR)+ "." + calendar.get(Calendar.MONTH)+"."+calendar.get(Calendar.DAY_OF_MONTH)+" "+calendar.get(Calendar.HOUR_OF_DAY)+":"+calendar.get(Calendar.MINUTE)+":"+calendar.get(Calendar.SECOND);
Log.i(logtag, "calendar.get(Calendar.YEAR)="+tidspunkt);
String tidspunkt2 = currentTime.getYear()+ "." + currentTime.getMonth()+"."+currentTime.getDay()+" "+currentTime.getHours()+":"+currentTime.getMinutes()+":"+currentTime.getSeconds();
Log.i(logtag, "currentTime.getYear()="+tidspunkt2);
currentTime.setYear(calendar.get(Calendar.YEAR));
currentTime.setMonth((calendar.get(Calendar.MONTH)));
currentTime.setDate(calendar.get(Calendar.DAY_OF_MONTH));
currentTime.setHours(calendar.get(Calendar.HOUR_OF_DAY));
currentTime.setMinutes(calendar.get(Calendar.MINUTE));
currentTime.setSeconds(calendar.get(Calendar.SECOND));
Log.i(logtag, "Date currentTime edited="+currentTime);
String tidspunkt3 = currentTime.getYear()+ "." + currentTime.getMonth()+"."+currentTime.getDay()+" "+currentTime.getHours()+":"+currentTime.getMinutes()+":"+currentTime.getSeconds();
Log.i(logtag, "currentTime.getYear() edited="+tidspunkt3);
Actual time when running: Mon 10th of January 2022, 22:29
Results:
Date currentTime=Mon Jan 10 22:29:53 GMT+01:00 2022 (correct date)
calendar.get(Calendar.YEAR)=2022.0.10 21:29:53 (wrong month, wrong hour)
currentTime.getYear()=122.0.1 22:29:53 (wrong year, wrong month, wrong day)
Date currentTime edited=Tue Jan 10 21:29:53 GMT+01:00 3922 (wrong year, wrong weekday, wrong hour)
currentTime.getYear() edited=2022.0.2 21:29:53 (wrong month, wrong day, wrong hour)
I need to save old dates as objects, and then be able to pull the correct year, month number, day number etc from those objects.
So I need an object which I can both extract dates from, and set to any old date I need.
This is why java.util.Date and java.util.Calendar are terrible APIs that you should replace with java.time. Have you read the doc on Date.setYear? Or seen that Calendar.JANUARY is 0?
You can use java.time with Android with desugaring.
Avoid legacy classes
Never use TimeZone, Calendar, Date. Do not waste your time trying to understand their bizarre behavior. Sun, Oracle, and the JCP community gave up on those classes years ago, and do should you. These terrible classes were years ago supplanted by the modern java.time classes defined in JSR 310.
java.time
Capture the current moment as seen in UTC (an offset of zero).
Instant instant = Instant.now() ;
The Instant class is a basic building block class with limited features. For more flexibility, convert to either OffsetDateTime or ZonedDateTime.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Asia/Tokyo" ) ) ;
Note that all three of these objects here, instant, odt, & zdt, all represent the very same simultaneous moment, the same single point on the time line.
To generate text representing a moment, you are working much too hard. Let DateTimeFormatter do the heavy lifting.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG ).withLocale( locale ) ;
String output = zdt.format( f ) ;
An implementation of java.time is built into Android 26+. For earlier Android, the latest tooling provides most of the java.time functionality via “API desugaring”. If that does not work for you, use a back-port of java.time, the ThreeTenABP project.

How to make start time and end time 12 am to 12 am?

I want my step counter to display steps from 12 am to 12 am I cant find a way to that is working. I am using Google's fitness API
here's the code:
Calendar cal = Calendar.getInstance();
Date today = new Date();
cal.setTime(today);
long endTime = cal.getTimeInMillis();
cal.add(Calendar.MONTH, -1);
long startTime = cal.getTimeInMillis();
java.text.DateFormat dateFormat = DateFormat.getDateInstance();
Log.e("History", "Range Start: " + dateFormat.format(startTime));
Log.e("History", "Range End: " + dateFormat.format(endTime));
//Check how many steps were walked and recorded in the last 7 days
final DataReadRequest readRequest = new DataReadRequest.Builder()
.aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
.bucketByTime(1, TimeUnit.DAYS)
.setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
.build();
final DataReadResult dataReadResult = Fitness.HistoryApi.readData(mGoogleApiClient, readRequest).await(1,TimeUnit.MINUTES);
java.time
You are using terrible old date-time classes that were supplanted years ago by the java.time classes defined in JSR 310.
LocalDate
First, get the date of interest. If you want “today”, you must specify a time zone.
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 ) ;
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.
First moment of the day
12 am to 12 am
A day does not always run from 12 AM to 12 AM!
Never assume when a day begins or ends. A day is not always 24 hours long, it can be 23, 23.5, 25, or any other number of hours dreamed up by the politicians defining the time zone. In some zones on some dates, the day may not start at 00:00, it may start at some other time such as 01:00. Let java.time determine when a day begins and ends.
Half-Open
Generally the best approach in defining a span-of-time is the Half-Open approach. In this approach, the beginning is inclusive while the ending is exclusive. This avoids the challenge of trying to determine the exact split-second end of the day. A day starts at the first moment of one date and runs up to, but does not include, the first moment of the next date.
ZonedDateTime zdtStart = ld.atStartOfDay( z ) ; // First moment of the day as seen in the wall-clock time used by the people of a particular region as defined arbitrarily by their politicians (a time zone).
ZonedDateTime zdtStop = ld.plusDays( 1 ).atStartOfDay( 1 ) ; // First moment of the day of the *following* date.
Epoch reference date, & granularity
The Google API for DataReadRequest.Builder::setTimeRange takes count of some granularity since some epoch reference date. Unfortunately, nether the limit of the granularity nor the epoch reference is specified – and there are many epoch references in use.
I will take a guess at seconds being the finest granularity, and guess at 1970-01-01T00:00Z being the epoch reference. This epoch is used by the java.time classes and by the terrible old java.util.Date class.
long secondsSinceEpoch_Start = zdtStart.toEpochSecond() ;
long secondsSinceEpoch_Stop = zdtStop.toEpochSecond() ;
Make your call to the API.
…
.setTimeRange(
secondsSinceEpoch_Start ,
secondsSinceEpoch_Stop ,
TimeUnit.SECONDS
)
…
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….
you can try like this
Date date1 = new Date();
SimpleDateFormat formatter1 = new SimpleDateFormat("MMddyyyy");
String format = formatter1.format(date1);
SimpleDateFormat formatter = new SimpleDateFormat("MMddyyyy hh:mm:ss");
Calendar cal = Calendar.getInstance();
Date today = formatter.parse(format+" 00:00:00");
cal.setTime(today);
long start = cal.getTimeInMillis();
System.out.println("start time:"+start);
Date date=formatter.parse(format+" 23:59:59");
cal.setTime(date);
long end = cal.getTimeInMillis();
System.out.println("end time: "+end);
Date tem= new Date();
cal.setTime(tem);
long present = cal.getTimeInMillis();
System.out.println(present);
If you need the start of day, you should set it as such:
Calendar cal = new GregorianCalendar();
cal.clear(Calendar.HOUR); cal.clear(Calendar.AM_PM);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// after all this we'd have the start of day.
// works good if extracted to separate method, which is the unfortunate truth of working with old calendar classes
// minus one milli because Fit API treats includes end of range
long end = cal.getTimeInMillis() - 1;
cal.add(Calendar.MONTH, -1);
long start = cal.getTimeInMillis();
I also may suggest to import and use Joda library for this (prefer Android-specific version).
Using Joda (and java.time package once Java 8 is available on Fit, with minor change), you can write equivalent code like this:
DateTime date = LocalDate.now().toDateTimeAtStartOfDay();
long end = date.getMillis() - 1;
long start = date.minusMonths(1).getMillis();

Java Calculate time until event from current time

I am trying to calculate the amount of time until the start of a soccer game.
This is what I know:
I have the time of an event:2016-08-16T19:45:00Z
I know the string format of it is "yyyy-M-dd'T'h:m:s'Z'"
I know the timezone is "CET".
I want to be able to calculate the difference from the current time to this date in days.
This is what I have tried:
String gameDate = "2016-03-19T19:45:00'Z'"
DateFormat apiFormat = new SimpleDateFormat("yyyy-M-dd'T'h:m:s'Z'");
apiFormat.setTimeZone(TimeZone.getTimeZone("CET"));
Date dateOfGame = apiFormat.parse(gameDate);
DateFormat currentDateFormat = new SimpleDateFormat("yyyy-M-dd'T'h:m:s'Z'");
currentDateFormat.setTimeZone(TimeZone.getTimeZone(userTimezone));
Date currentDate = apiFormat.parse(currentDateFormat.format(new Date()));
long lGameDate = dateOfGame.getTime();
long lcurrDate = currentDate.getTime();
long difference = lGameDate - lcurrDate;
Date timeDifference = new Date(difference);
String daysAway = new SimpleDateFormat("d").format(timeDifference);
Integer intDaysAway = Integer.parseInt(daysAway);
You are probably wondering why I don't just get the date of the game (8) and subtract the current date (19). I don't do that in the edge case that the current date is the 29th and the game date is the 3rd of the next month.
Nobody has yet provided a Java 8 java.time answer...
String eventStr = "2016-08-16T19:45:00Z";
DateTimeFormatter fmt = DateTimeFormatter.ISO_ZONED_DATE_TIME;
Instant event = fmt.parse(eventStr, Instant::from);
Instant now = Instant.now();
Duration diff = Duration.between(now, event);
long days = diff.toDays();
System.out.println(days);
tl;dr
ChronoUnit.DAYS.between(
Instant.parse( "2016-08-16T19:45:00Z" ).atZone( ZoneId.of( "Europe/Paris" ) ),
Instant.parse( "2016-08-23T12:34:00Z" ).atZone( ZoneId.of( "Europe/Paris" ) )
);
Define “days”
There are two ways to count a number of days. Your Question is not quite clear which you intended. This Answer shows example code for both ways.
Calendar-based days by dateApply the intended time zone to determine the dates of the start and the the stop. A date is determined by zone, as for any given moment the date varies around the globe being “tomorrow” towards the east while “yesterday” to the west depending where you sit. For example a few minutes after midnight in Paris France a new day while still “yesterday” in Montréal Québec.
24-hour chunks of timeIf you consider only generic days of 24-hour chunks of time while ignoring anomalies such as Daylight Saving Time (DST), then you get the total number of seconds between the beginning and ending moment and divide that by 24-hours. In this approach we ignore the calendar and its dates.
Example of the differences: Start late Monday night, an hour before midnight. Stop an hour after midnight on Wednesday morning. For 24-hour chunks that total of 26 hours is a single day. But by calendar dates that would two elapsed days, having touched three calendar days.
Why two days if we touched three? Date-time work commonly uses the Half-Open approach where the beginning is inclusive while the ending is exclusive.
Avoid legacy date-time classes
The modern way to do this work is with the java.time classes rather than the troublesome old legacy date-time classes (Date, Calendar, etc.).
The Answer by dcsohl is correct but could be shorter. No need to be explicit about the DateTimeFormatter as the input string is in one of the standard ISO 8601 formats used by default.
I know the string format of it is "yyyy-M-dd'T'h:m:s'Z'"
As part of the ISO 8601 standard, the Z on the end is short for Zulu and means UTC.
String startInput = "2016-08-16T19:45:00Z" ;
String stopInput = "2016-08-23T12:34:00Z" ;
Parse as Instant objects. 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 start = Instant.parse( startInput );
Instant stop = Instant.parse( stopInput );
I know the timezone is "CET".
Time zone is irrelevant to parsing the strings. But time zone does matter in terms of calculating elapsed days if counting by calendar dates rather than by 24-hours per generic day.
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 or CET as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Europe/Paris" );
Adjust both our start and stop moments into that time zone.
ZonedDateTime zdtStart = start.atZone( z );
ZonedDateTime zdtStop = stop.atZone( z );
The java.time framework provides two classes for spans of time:
Period for years-months-days
Duration for hours-minutes-seconds
The Period class takes a pair of LocalDate objects, date-only values without time-of-day and without time zone. We can extract LocalDate objecs from our ZonedDateTime objects. Remember that date is determined by zone. So it is crucial that we adjusted our UTC values into ZonedDateTime objects.
Period p = Period.between( zdtStart.toLocalDate() , zdtStop.toLocalDate() );
You can interrogate that Period for the number of years and months and days of that span of time.
If you want a total number of days, use the ChronoUnit enum.
long days = ChronoUnit.DAYS.between( zdtStart , zdtStop );
The above is for calendar date-based counting of days.
If you want to count by generic chuncks of 24-hour periods, use the Duration class as shown in the Answer by dcsohl.
Duration.between( start , stop ).toDays()
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.
Try doing/ using TimeUnit:
Example:
final String gameDate = "2016-03-19T19:45:00Z";
final SimpleDateFormat apiFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
apiFormat.setTimeZone(TimeZone.getTimeZone("CET"));
final Date dateOfGame = apiFormat.parse(gameDate);
final long millis = dateOfGame.getTime() - System.currentTimeMillis();
System.out.println(dateOfGame.getTime() - System.currentTimeMillis());
final String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(hms);
This will print the output:
72:57:34
72 hours, 57 minutes and 34 seconds from now until gameDate
You could simply take the result from long difference = lGameDate - lcurrDate;, which is the difference in milliseconds, and convert to whatever unit you like.
For example, in days: int days = difference/1000/3600/24;
This is what you need:
public static void main (String[] args) throws Exception
{
String gameDate = "2016-03-19T19:45:00Z";
DateFormat apiFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
apiFormat.setTimeZone(TimeZone.getTimeZone("CET"));
Date dateOfGame = apiFormat.parse(gameDate);
long now = new Date().getTime() / (3600000 * 24);
long game = dateOfGame.getTime() / (3600000 * 24);
System.out.println(now - game);
}
This will work because you are getting number of full days since epoch for date of game and now and just need to find difference. Other solutions will have errors in border cases.
Your variable difference contains the time difference in milliseconds. To convert those milliseconds to days, hours, minutes, seconds I recommend you to use the java.util.concurrent.TimeUnit class.
Example:
final long durationMinutes = TimeUnit.MILLISECONDS.toMinutes(difference);
final long durationSeconds = TimeUnit.MILLISECONDS.toSeconds(difference)
- TimeUnit.MINUTES.toSeconds(durationMinutes);
final long durationMillis = difference- TimeUnit.MINUTES.toMillis(durationMinutes)
- TimeUnit.SECONDS.toMillis(durationSeconds);
final String durationString = String.format("%d min, %d s, %d ms", durationMinutes, durationSeconds, durationMillis);
First of all your date format is wrong. It should be yyyy-MM-dd'T'HH:mm:ss'Z' instead of yyyy-M-dd'T'h:m:s'Z'.
Also, your gameDate String should end in Z and not 'Z'.
You can easily get the difference in days by just calling the getTime() function on current and given dates. You don't even have to format the current date.
Here is the code snippet:
public static void main (String[] args) throws Exception
{
String gameDate = "2016-03-19T19:45:00Z";
DateFormat apiFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
apiFormat.setTimeZone(TimeZone.getTimeZone("CET"));
Date dateOfGame = apiFormat.parse(gameDate);
long difference = new Date().getTime() - dateOfGame.getTime();
System.out.println((double)difference / (3600000d * 24d));
}
You can do the rounding on the result if you want.

Number of days between two dates (excluding these two dates)

I searched for this is SO there are so many post asking this question but all the answers is difference In Milliseconds / (24* 1000 * 60 * 60) that gives the number of 24 Hrs between two dates .
but i need the number of days between 2 dates.
I.e. if date1 is 09/09/13 09:00 and date2 is 10/09/13 22:00 I need the difference as 0 and not 1 because date1 and date2 are consecutive days (even if there is more than 24 hour gap between them).
Note: I know the removing the time part and using the difference In Milliseconds / (24* 1000 * 60 * 60) method. I am looking for a better solution.
update: the app is first used on 09/09/13 09:00 its a Wednesday then the app was used on 10/09/13 22:00` its Thursday. now the user has used the app both Wednesday and Thursday even though there is more than 24 hour gap. now if i calculate the number of 24 hours between the 2 dates it gives one. as there is a day gap between 2 dates. i need it to give zero as the user used it Wednesday and Thursday there is NO DAY BETWEEN WEDNESDAY AND THURSDAY.
hope you understood my question. if you still didn't just leave it, i tried by best explaining.
Here's a simple solution:
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
while(calendar.getTime().before(endDate))
{
noOfDays++;
calendar.add(Calendar.DAY_OF_MONTH,1);
}
Where startDate and endDate are instances of the Date class.
Note: You need to initialize the date objects so that they have the same time but only differ in their dates. Setting them both to 12 AM should do the trick:
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.text.SimpleDateFormat;
import java.text.ParseException;
public class test {
public static void main(String[] args) throws ParseException {
String dateStart = "09/09/13 09:00";
String dateStop = "10/09/13 22:00";
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date1 = format.parse(dateStart);
Date date2 = format.parse(dateStop);
// calculate difference in milliseconds
long diff = (date2.getTime() - date1.getTime()) - 86400000;
diff = (diff <= 0 ? 0 : diff);
System.out.println(TimeUnit.MILLISECONDS.toDays(diff));
}
}
This will give the difference between 2 dates. And subtract a day (if its negative, it sets the difference to 0 day). This will work as long as dateStop is greater than dateStart, otherwise it will just print 0;
I have avoided using Joda Time for ages, but this past week I got round to using it for exactly this issue. And it was well worth it!
It is very easy to introduce some strange date handling bugs when dealing with plain Java - for example what happens when daylight savings time changes. Joda Time builds all these exceptions in already.
Check related question here:
Number of days between two dates in Joda-Time
Update
As of Java 8, the time & date functionality has been improved, and the Joda Time team suggests using that instead of their library. Here's what they say on the landing page:
Note that from Java SE 8 onwards, users are asked to migrate to
java.time (JSR-310) - a core part of the JDK which replaces this
project.
Thanks to Basil Bourque for the comment.
You can use this trick: if date1 is before date2 you can set hour in date1 to 1 and in date2 to 0. This way hour part in entire time difference will never be greater than 24h, so will not affect calculations so only days/months/years will matter.
Here is code example
public static long daysBetween(Date date1, Date date2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
Calendar c2 = Calendar.getInstance();
c2.setTime(date2);
if (date1.before(date2)) {
c1.set(Calendar.HOUR_OF_DAY, 1);
c2.set(Calendar.HOUR_OF_DAY, 0);
} else {
c2.set(Calendar.HOUR_OF_DAY, 1);
c1.set(Calendar.HOUR_OF_DAY, 0);
}
return (c2.getTimeInMillis() - c1.getTimeInMillis())
/ (24 * 60 * 60 * 1000);
}
//DEMO
public static void main(String[] args) throws Exception {
DateFormat df = new SimpleDateFormat("dd/MM/yy hh:mm");
Date date1 = df.parse("09/09/13 09:00");
Date date2 = df.parse("11/09/13 22:00");
System.out.println(daysBetween(date1, date2));
}
Output: 1
For dates 11/09/13 09:00 09/09/13 22:00 result will be -1 since date1 is after date2
tl;dr
ChronoUnit.DAYS.between(
earlierInstant.atZone( ZoneId.of( "Africa/Tunis" ) ).toLocalDate() ,
Instant.now().atZone( ZoneId.of( "Africa/Tunis" ) ).toLocalDate()
)
java.time
The modern approach uses the java.time classes that supplanted the troublesome old date-time classes such as Date & Calendar.
If you want to calculate the number of elapsed days as the number of calendar dates rather than the number of 24-hour chunks of time, use a date-only class rather than a date-time class.
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" ) ;
Generally best to think, work, log, serialize, and exchange values in UTC. For that, use 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 earlier = Instant.now() ;
…
Instant later = Instant.now() ;
Serialize to text in standard ISO 8601 format by calling Instant::toString and Instant::parse.
To get your elapsed dates, apply a time zone (ZoneId) to get ZonedDateTime objects.
ZonedDateTime zdtEarlier = earlier.atZone( z ) ;
ZonedDateTime zdtLater = later.atZone( z ) ;
Extract the date-only values.
LocalDate ldEarlier = zdtEarlier.toLocalDate() ;
LocalDate ldLater = zdtLater.toLocalDate() ;
Now we can get the elapsed days between the dates.
long daysElapsed = ChronoUnit.DAYS.between( ldEarlier , ldLater ) ;
This calculation is done per the Half-Open approach where the beginning is inclusive while the ending is exclusive. So, for example, a month starts with the first day of the month and runs up to, but does not include, the first day of the following month. Using this approach consistently throughout your business logic, database queries, and so on will make your codebase less error-prone and easier to read/debug/maintain.
I understand you want to use a fully-Open approach where both beginning and ending is exclusive. I strongly suggest you reconsider that position. But if you insist, simply subtract 1 from our calculation above.
long daysElapsedFullyOpen = ( ChronoUnit.DAYS.between( ldEarlier , ldLater ) - 1 ) ; // Subtract 1 to get a fully-Open answer. NOT recommended.
By the way, you may want to consider the Period class in your work. Similarly, you may find useful the LocalDateRange class found in the ThreeTen-Extra project.
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.

Categories

Resources