Difference between two dates, in days, varies - java

Date d = new Date(today.getTimeInMillis());
Date d1 = new Date(dueDate.getTimeInMillis());
int daysUntil = (int) ((d1.getTime() - d.getTime())/ (1000 * 60 * 60 * 24));
Using the above code, where today is a calendar set to 00:00 on the current day, and dueDate is set to 00:00 on the date I am comparing today to, my results from this differ.
There is something in this which varies, making my output either x or x+1 where x is the correct answer.
What is the issue here, and what can I do to make it more stable?

Vague Question
You do not provide actual values, so we cannot determine precisely the problem. We do not know what the today and dueDate variables are.
Outmoded
The question is now outmoded, as the troublesome old date-time classes including java.util.Date/.Calendar have been supplanted by the new java.time framework. See Tutorial. Defined by JSR 310, inspired by Joda-Time, and extended by the ThreeTen-Extra project.
In java.time:
An Instant is a moment on the timeline in UTC.
A ZoneId represents a time zone. Use proper time zone names, never the 3-4 letter codes like "EST" or "IST" as they are neither standardized nor unique.
Conceptually, ZonedDateTime = Instant + ZoneId.
ThreeTen-Extra
Unfortunately, java.time does not include a facility for calculating days elapsed between date-time values. We can use the ThreeTen-Extra project and its Days class with between method to provide that calculation. The ThreeTen-Extra project is a collection of features deemed non-essential for java.time during the JSR process.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now ( zoneId );
ZonedDateTime then = now.minusDays ( 4 );
ZonedDateTime due = now.plusDays ( 3 );
Integer days = org.threeten.extra.Days.between ( then , due ).getAmount ();
Dump to console.
System.out.println ( "From then: " + then + " to due: " + due + " = days: " + days );
From then: 2015-10-31T16:01:13.082-04:00[America/Montreal] to due: 2015-11-07T16:01:13.082-05:00[America/Montreal] = days: 7
Joda-Time
For Android or older versions of Java, use the excellent Joda-Time library.
The Days class is smart and handles anomalies such as Daylight Saving Time (DST).
Note that unlike java.util.Date, a Joda-Time DateTime object knows its own time zone.
// Specify a time zone rather than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "America/Regina" ); // Or "Europe/London".
DateTime now = new DateTime( timeZone );
DateTime startOfToday = now.withTimeAtStartOfDay();
DateTime fewDaysFromNow = now.plusDays( 3 );
DateTime startOfAnotherDay = fewDaysFromNow.withTimeAtStartOfDay();
Days days = Days.daysBetween( startOfToday, startOfAnotherDay );
Dump to console…
System.out.println( days.getDays() + " days between " + startOfToday + " and " + startOfAnotherDay + "." );
When run…
3 days between 2014-01-21T00:00:00.000-06:00 and 2014-01-24T00:00:00.000-06:00.

There are mainly two reasons why your code is broken:
second parts or millisecond fractions (you might have overlooked)
daylight saving effects
I demonstrate and explain the second reason.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = sdf.parse("2016-03-20");
Date d2 = sdf.parse("2016-03-28");
int daysUntil = (int) ((d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
System.out.println(daysUntil); // 7 (should be 8)
The code was run in timezone "Europe/Berlin". Due to the change from winter time to summer time causing a jump of clocks by one hour forward on 2016-03-27 at 2 am, there is one hour missing. One day has only 23 hours so the division by 24 yields zero resulting in counting one day less.
What can you do else?
Your workaround adding 1000 milliseconds to dueDate sounds as if you have overlooked possible millisecond deltas in your input. This might solve a special case but will usually not be sufficient to solve the daylight saving problem, too. Whatever you choose on base of java.util.Date it is a more or less an evil hack.
The best I have in mind (within the scope of Android-built-in stuff) is to construct an instance of java.util.GregorianCalendar and to add successively one day after one until you have passed the due-date, and then count how many days you have added. Not elegant and errorprone because varying millisecond parts can easily be overlooked here, too.
Otherwise you can try various external libraries for this task. There are four available on Android which can calculate elapsed days in an easy way.
Date4J (main advantage: very small but else limited features)
Threeten-ABP (uses backport of Java-8)
Joda-Time-Android (based on Joda-Time)
Time4A (my own library for Android)

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 | How to determine if a calendar object is a year old?

If I have a calendar object with a date of 1/8/2012, how would I determine if it has been at least one year since the object's creation?
java.time
The old java.util.Date/.Calendar classes have been supplanted by the new java.time framework built into Java 8 and later (Tutorial). If you really want .Calendar, search any of the hundreds of existing such questions already posted on StackOverflow.
Here is some example code in java.time. The LocalDate class represents a date-only value without time-of-day or time zone. But note that determining today’s date requires a time zone.
// Then.
LocalDate then = LocalDate.parse ( "2012-01-08" );
// Now.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
LocalDate today = LocalDate.now ( zoneId );
// Elapsed.
Period period = Period.between ( then , today );
int years = period.getYears ();
// Business logic.
Boolean atLeastOneYearHasPassed = ( years >= 1 );
Dump to console.
System.out.println ( "From then: " + then + " to today: " + today + ", atLeastOneYearHasPassed: " + atLeastOneYearHasPassed + ", years: " + years );
When run.
From then: 2012-01-08 to today: 2015-10-17, atLeastOneYearHasPassed: true, years: 3
First of all, you need two datestamps; one for the account creation date, and the second one for "now".
Then you simply turn the two datestamps into scalar values with the same units (e.g. using Calendar.getTime() gives you milliseconds since some "epoch"), subtract one from the other, see if the difference is more, less or equal to 1 year == 365 days (in the relevant units).
If you are talking about "calendar years" (e.g. taking account of leap years, etcetera) then it gets more complicated, and the rules are potentially locale specific.
I recommend that you use the java.time classes rather than the old Calendar API. If you are new to this, start by reading the Oracle Java tutorial "Lesson: Date-Time Overview"

Create instance of joda DateTime from integer representing # of days since epoch?

In my application, it saves a preference which is an integer that is the number of days since the epoch. (not relevant but it is used to create backups every x days)
Given this value, how can I reliably create an instance of joda DateTime?
I'm tempted to convert it to milliseconds by doing the multiplication value * 24 * 60 * 60 * 1000 but this will be wrong due to astronomy / solar time?
Multiplying number of days into the number of milliseconds might be more readable if you use a library function. I highly recommend using Joda. :)
You have a number of days since epoch (GMT), and you want a DateTime (date + time + timezone). At a bare minimum, before you get further, you'll need to specify how you want to treat the time and timezone calculation.
The simplest way (which might not be what you intend) would be to create an instant in the local timezone representing the beginning of epoch, and then use plusDays to add the right number of days:
// in class - note that this will cache the current default timezone
private static final DateTime EPOCH_START_INSTANT = new DateTime(0);
// West of Greenwich, this will actually represent the "day" before.
// Day 0 will be Dec 31, 1969, local time.
DateTime localTime = EPOCH_START_INSTANT.plusDays(yourDayCount);
For the purpose of creating a backup every X days, you might instead want a LocalDate initialized at epoch (January 1, 1970), plus the number of days you want. That could then be changed to a specified local time relatively easily.
// in class
private static final EPOCH_LOCALDATE = new LocalDate(1970, 1, 1);
private static final THREE_AM = new LocalTime(3, 0);
LocalDate localDate = EPOCH_LOCALDATE.plusDays(yourDayCount);
// Midnight (or closest valid time thereto) in the default time zone
DateTime startOfDay = localDate.toDateTimeAtStartOfDay();
// 3 AM in the default time zone
DateTime threeAM = localDate.toDateTime(THREE_AM);
The answer by Jeff Bowman is correct.
I'll show the same idea in the java.time framework, intended to succeed Joda-Time.
java.time
Java 8 and later has the new java.time framework built-in. These new classes supplant the old java.util.Date/.Calendar classes. They are inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
I am assuming your count-of-day-from-epoch is in UTC. So we can use the Instant class, basically a count of nanoseconds from the first moment of 1970 in UTC.
long myCountOfDays = 16_721L;
Instant instant = Instant.EPOCH.plus ( myCountOfDays , ChronoUnit.DAYS );
Let's adjust into a time zone. Choosing Montreal arbitrarily. Use a proper time zone name, never the 3-4 letter codes like "EST" or "IST".
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
Dump to console.
System.out.println ( "myCountOfDays: " + myCountOfDays + " from epoch: " + Instant.EPOCH + " in UTC is: " + instant + " and in Montréal is: " + zdt + "." );
When run.
myCountOfDays: 16721 from epoch: 1970-01-01T00:00:00Z in UTC is: 2015-10-13T00:00:00Z and in Montréal is: 2015-10-12T20:00-04:00[America/Montreal].
According to the FAQ:
Joda-Time does not support leap seconds. Leap seconds can be supported by writing a new, specialized chronology, or by making a few enhancements to the existing ZonedChronology class. In either case, future versions of Joda-Time will not enable leap seconds by default. Most applications have no need for it, and it might have additional performance costs.
That suggests to me that you need not worry about that aspect.
But rather than doing the math, I would use DateTime#plusDays or MutableDateTime#addDays instead, using The Epoch as your starting point.
I assume, though, that your "days since The Epoch" is allowing for leap days (and that you're using the Gregorian chronology so JodaTime is, too).

Compensating for BST when calculating difference between 2 times

I need some help or a pointer in the right direction.
I am trying to get the difference between 2 times. I am in UK on GMT with timezone set to adjust for daylight saving automatically.
When I preform the following it is always 1 hour out unless, I switch off automatically adjust for daylight saving.
String strDate = new java.text.SimpleDateFormat("HH:mm:ss").format(new Date().getTime() - oldDate.getTime());
If I run the following there is not the 1 hour difference the 2.
System.out.println("Current time " + Formats.HOURMIN.formatValue(new Date().getTime()));
System.out.println("Old time " + Formats.HOURMIN.formatValue(oldDate.getTime()));
Any assistance would be appreciated.
The cardinal rule for calculating time intervals when different timezones are involved is to make sure to convert the times to UTC before subtracting.
Each time, no matter what zone and DST offset is in effect at the time (pun somewhat intended), converts to a unique UTC instant. Once you have the times in UTC, calculating the difference is a simple subtraction. The result is time-zone-independent.
The java.util.Date class has no time zone attached to it yet confusingly uses your default time zone when rendering a string. I'm guessing this may be your problem. One of many reasons to avoid java.util.Date/Calendar classes.
The Joda-Time 2.3 library makes this kind of work easier. Look at the Period, Duration, and Interval classes.
In contrast to a java.util.Date, in Joda-Time a DateTime instance does indeed know its assigned time zone.
The ISO 8601 standard defines a way to describe durations as hours, minutes, and such in a PnYnMnDTnHnMnS format. I use that in my example code below. Joda-Time offers other ways as well.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
DateTimeZone timeZone = DateTimeZone.forID( "Europe/London" );
DateTime dateTimeNew = new DateTime( timeZone );
DateTime dateTimeOld = dateTimeNew.minusHours( 2 );
Period period = new Period( dateTimeOld, dateTimeNew );
Dump to console…
System.out.println( "dateTimeNew: " + dateTimeNew );
System.out.println( "dateTimeOld: " + dateTimeOld );
System.out.println( "period: " + period );
When run…
dateTimeNew: 2014-01-02T23:19:45.021Z
dateTimeOld: 2014-01-02T21:19:45.021Z
period: PT2H

How to add one day to a date? [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

Categories

Resources