This question already has answers here:
Java: Date from unix timestamp
(11 answers)
Converting Long to Date in Java returns 1970
(12 answers)
android timestamp parsing gone wrong(always in 1970)
(4 answers)
Closed 3 years ago.
I want to convert 1574348400 value to date format using code:
public class Main {
public Main() {
long value = 1574348400;
String dateString = new SimpleDateFormat("EEEE dd MMMM, yyyy").format(new Date(value));
System.out.println("Formated time: " + dateString);
}
public static void main(String[] args) {
new Main();
}
}
I want to get the output as: Wednesday 20 November, 2019 but I'm getting Monday 19 January, 1970. How to get the current date not the 1970's date?
Parse your time (in seconds) using java.time, it provides a method for epoch seconds...
public static void main(String[] args) {
// your seconds
long seconds = 1574348400;
// same in millis
long millis = 1574348400000L;
// find out the zone of your system
ZoneId systemDefaultZoneId = ZoneId.systemDefault();
// or set a specific one
ZoneId utcZoneId = ZoneId.of("UTC");
// parse a ZonedDateTime of your system default time zone from the seconds
ZonedDateTime fromSecsSysDefZone = ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds),
systemDefaultZoneId);
// parse a ZonedDateTime of UTC from the seconds
ZonedDateTime fromSecsUtc = ZonedDateTime.ofInstant(Instant.ofEpochSecond(seconds),
utcZoneId);
// parse a ZonedDateTime of your system default time zone from the milliseconds
ZonedDateTime fromMillisSysDefZone = ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis),
systemDefaultZoneId);
// parse a ZonedDateTime of UTC from the milliseconds
ZonedDateTime fromMillisUtc = ZonedDateTime.ofInstant(Instant.ofEpochMilli(millis),
utcZoneId);
// print the ones that were created using your default time zone
System.out.println("from seconds:\t"
+ fromSecsSysDefZone.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
System.out.println("from millis:\t"
+ fromMillisSysDefZone.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// print a check for equality
System.out.println("Both ZonedDateTimes are "
+ (fromSecsSysDefZone.equals(fromMillisSysDefZone) ? "equal" : "different"));
System.out.println("————————————————————————————————");
// print the ones that were created using UTC
System.out.println("from seconds:\t"
+ fromSecsUtc.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
System.out.println("from millis:\t"
+ fromMillisUtc.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// print a check for equality
System.out.println("Both ZonedDateTimes are "
+ (fromSecsUtc.equals(fromMillisUtc) ? "equal" : "different"));
}
The output produced by this code (on my system) is
from seconds: 2019-11-21T16:00:00+01:00[Europe/Berlin]
from millis: 2019-11-21T16:00:00+01:00[Europe/Berlin]
Both ZonedDateTimes are equal
————————————————————————————————
from seconds: 2019-11-21T15:00:00Z[UTC]
from millis: 2019-11-21T15:00:00Z[UTC]
Both ZonedDateTimes are equal
If you have to use Java 6 or 7, then you can use the ThreeTenBackport-Project on Github, which enables (most) functionality of java.time in those two older versions.
Its use is explained on a separate website.
Wrong value. Try:
long value = 1574348400000L;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class BasicWebCrawler {
public BasicWebCrawler() {
long value = 1574348400000L;
Date date = new Date(value);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, -1);
Date minusOne = cal.getTime();
String dateString = new SimpleDateFormat("EEEE dd MMMM, yyyy").format(minusOne);
System.out.println("Formated time: " + dateString);
}
public static void main(String[] args) {
new BasicWebCrawler();
}
}
output : Formated time: Wednesday 20 November, 2019
Your first issue is: You are using seconds instead of milliseconds, new Date(long) the value of long is in milliseconds.
See the Java 6 java.util.Date Documentation here
Your second issue is: When using Java 6 Date you need to know where the value in milliseconds was determined, if it's not in your timezone then you will need to make a conversion. Take the following code for example:
String zeroDateString = new SimpleDateFormat("EEEE dd MMMM, yyyy hh:mm").format(new Date(0));
System.out.println("Formated time -- zeroDateString = " + zeroDateString);
The output of new Date(0) in NYC, NY, USA will be Wednesday December 31, 1969 19:00 (the timezone of New-York City is EST which is GMT-05:00) while in Rome, Italy the output of the same code will be Thursday 01 January 1970 01:00 (the timezone of Rome, Italy is GMT+01:00)
If you need all your data to be according to GMT then you will need to make adjustment and/or calculation according to your timezone in relation to GMT.
Related
This question already has answers here:
Java, Calculate the number of days between two dates [duplicate]
(10 answers)
Calculating the difference between two Java date instances
(45 answers)
The difference between 2 Instants in Calendar Days
(4 answers)
Closed 1 year ago.
I have a scenario where epoch time is in string . I need to convert this to number of days ago from current time .
Eg:
String epoch = "1600852773514";
Date expiry = new Date(Long.parseLong(epoch));
Expiry gives me Wed Sep 23 14:49:33 IST 2020 .But I want to get number of days from today to the time 'epoch' . Like epoch is 240 days ago from today.
If expiry > 30 days
pass
else
fail
You can do something like this:
Date expiry = /* ... */;
Date now = new Date();
long days = (now.getTime() - expiry.getTime()) / 86_400_000;
if (days > 30) /* ... */
So we take the difference of the time in milliseconds:
long diff = (now.getTime() - expiry.getTime());
If we divide by 86.000.000 (this is how many milliseconds a day has), we get the number of past days.
As an alternative, you could use java.time (since Java 8) and count the days between two dates:
public static void main(String[] args) {
// example String
String epoch = "1618991673000";
// parse it to a long
long epochMillis = Long.parseLong(epoch);
// then create an Instant from that long value
Instant instant = Instant.ofEpochMilli(epochMillis);
// and convert it to an OffsetDateTime at UTC (+00:00)
OffsetDateTime odt = OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);
// get today's date (only, no time of day considered)
LocalDate today = LocalDate.now();
// and extract the date of the OffsetDateTime
LocalDate then = odt.toLocalDate();
// count the days between the two dates
long daysGone = ChronoUnit.DAYS.between(then, today);
// and print the result...
System.out.println("Days between " + then
+ " and today (" + today + "): " + daysGone);
}
This outputs (today, 21st of May 2021):
Days between 2021-04-21 and today (2021-05-21): 30
Afterwards, you can easily check if the amount of days is greater or less than allowed in your scenario.
Converting to Instance's and using Duration class:
String epoch = "1600852773514";
Instant start = Instant.ofEpochMilli(Long.parseLong(epoch));
Instant now = Instant.now();
Long diff = Duration.between(start,now).toDays();
System.out.println(diff);
This question already has answers here:
TimeZone problem in Java
(3 answers)
GregorianCalendar Class in Java
(3 answers)
Calendar returns date in wrong time zone
(5 answers)
Closed 2 years ago.
I have to use the date time which I receive by user, and convert that time to UTC from the given time. Right now, all the solutions are working, but not as I needed. First, it converts to the time zone, but I don't want to initially convert. I have to set that timezone on my date and then convert that time to UTC. Right now, each and every solution shows that I have to pass date and time, and then I am getting updated date and time with the time zone which I provide, and then converts to the UTC. This was not my question.
My user will send me date time of any timezone, and my server will be running on UTC time zone. I will get the zone id from the front end. I want to convert that date time to UTC and verify with my other conditions. It might be possible that I will get UTC-7 time in one request, and then after in next request I will get UTC+5:30. So, all the time should be converted to the UTC and I am not able to set timezone on date.
I wanted to set the specific timezone to date, and I am getting the date and time of that timezone, but I'm not able to set the exact timezone. Here, I am adding my code please tell me where I am wrong:
Calendar laCalendar = Calendar.getInstance();
laCalendar.set(2020, 8, 14, 00, 00);
Date losAngelesDate = laCalendar.getTime();
System.out.println("LA Date1===>" + losAngelesDate);
SimpleDateFormat simpleTimeFormatForUSA = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
simpleTimeFormatForUSA.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
String americaDateString = simpleTimeFormatForUSA.format(laCalendar.getTime());
SimpleDateFormat dateFormatUSA = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
losAngelesDate = dateFormatUSA.parse(americaDateString);
System.out.println("LA Date2===>" + losAngelesDate);
Date utcDate = losAngelesDate;
Calendar calendar = Calendar.getInstance();
calendar.setTime(utcDate);
TimeZone timeZone = TimeZone.getTimeZone("UTC");
SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
simpleTimeFormat.setTimeZone(timeZone);
String utcTime = simpleTimeFormat.format(calendar.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
utcDate = dateFormat.parse(utcTime);
System.out.println("UTC date====>" + utcDate);
And my output is
LA Date1===>Mon Sep 14 00:00:56 UTC 2020
LA Date2===>Sun Sep 13 17:00:00 UTC 2020
UTC date====>Sun Sep 13 17:00:00 UTC 2020
Here you can see that my DateTime is converted, but time zone is still UTC and I wanted to update that.
Here, is how I would write it using Java 8 Date/Time APIs.
public static void main(String[] args)
{
System.out.println("UTC");
toTimeZone(new Date(), TimeZone.getTimeZone(ZoneId.of("UTC")));
System.out.println("America/Los_Angeles");
toTimeZone(new Date(), TimeZone.getTimeZone(ZoneId.of("America/Los_Angeles")));
}
public static void toTimeZone(Date date, TimeZone timeZone)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Instant epochMillisInstant = Instant.ofEpochMilli(calendar.getTimeInMillis());
LocalDateTime localDateTime = LocalDateTime.ofInstant(epochMillisInstant, ZoneId.systemDefault());
ZonedDateTime dateTimeToConvert = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
ZonedDateTime dateTimeWithTimeZone = dateTimeToConvert.withZoneSameInstant(timeZone.toZoneId());
String formattedDateForNewTimeZone = dateTimeWithTimeZone.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a"));
System.out.println(formattedDateForNewTimeZone);
}
Using Just Java 8 Date/Time APIs - Shorter Version
public static void main(String[] args) {
System.out.println("UTC");
toTimeZone(LocalDateTime.now(),"UTC");
System.out.println("America/Los_Angeles");
toTimeZone(LocalDateTime.now(),"America/Los_Angeles");
}
private static void toTimeZone(LocalDateTime localDateTime, String timeZone) {
ZonedDateTime localDateTimeToConvert = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
ZonedDateTime zonedDateTime = localDateTimeToConvert.withZoneSameInstant(ZoneId.of(timeZone));
String formattedDateForNewTimeZone = zonedDateTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a"));
System.out.println(formattedDateForNewTimeZone);
}
Before you convert the Calendar to a Date, set the Timezone to your preference.
For example:
import java.util.Calendar;
import java.util.TimeZone;
public class Timezone{
public static void main(String []args){
Calendar laCalendar = Calendar.getInstance();
TimeZone timezone = TimeZone.getTimeZone("UTC");
laCalendar.set(2020, 8, 14, 00, 00);
laCalendar.setTimeZone(timezone);
java.util.Date losAngelesDate = laCalendar.getTime();
System.out.println(losAngelesDate.toString());
}
}
I want to check if my Date value from -
Date d = convertCurrentTimeToSpecificTimeZone("America/Chicago", 2, 30);
falls in the range of 10am to 6 pm.
I found some similar links on StackOverflow similar question and used some of the code from this thread.
All I want to check if the current time from any timezone falls under the range of 10 am to 6 pm. If Yes, print "yes" else print "no".
Currently for below code:
String string1 = "10:11:13";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
System.out.println(calendar1.getTime().toString());
It just prints the 10:11 am time of 1970 year. Like this - Fri Jan 02 10:11:13 IST 1970.
But I want to check if today's or any future date time falls in the range of 10 am to 6pm.
Below is the code reference:
public static Date convertCurrentTimeToSpecificTimeZone(String timeZone, int increaseDateBy,
int increaseMinutesBy) {
Calendar calendar = Calendar.getInstance();
TimeZone fromTimeZone = calendar.getTimeZone();
TimeZone toTimeZone = TimeZone.getTimeZone(timeZone);
calendar.setTimeZone(fromTimeZone);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
increaseCalenderDateBy(calendar, increaseDateBy);
increaseCalenderMinuteBy(calendar, increaseMinutesBy);
return calendar.getTime();
}
public static void getTimeBetweenRange() throws ParseException {
String string1 = "10:11:13";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
System.out.println(calendar1.getTime().toString());
String string2 = "18:49:00";
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
System.out.println(calendar2.getTime().toString());
Date d = convertCurrentTimeToSpecificTimeZone("America/Chicago", 2, 30);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
System.out.println(calendar3.getTime().toString());
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
// checkes whether the current time is between 14:49:00 and 20:11:13.
System.out.println(true);
} else
System.out.println(false);
}
So the output for my below code is:
Fri Jan 02 10:11:13 IST 1970
Fri Jan 02 18:49:00 IST 1970
Fri Jan 31 03:15:07 IST 2020
It’s not very clear. For this answer I am assuming that all of your times are to be understood in America/Chicago time zone. Please revert if this was not what you intended.
java.time
ZoneId zone = ZoneId.of("America/Chicago");
ZonedDateTime zdt = ZonedDateTime.now(zone).plusDays(2).plusMinutes(30);
LocalTime rangeStart = LocalTime.parse("10:11:13");
LocalTime rangeEnd = LocalTime.parse("18:49:00");
LocalTime time = zdt.toLocalTime();
if (!time.isBefore(rangeStart) && time.isBefore(rangeEnd)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
When I ran this code snippet just now (at 11:30 Chicago time), the output was:
Yes
I am using java.time, the modern Java date and time API, and recommend that you do the same. It’s so much nicer to work with than the old, outdated and poorly designed classes Date, SimpleDateFormat, Calendar and TimeZone.
A LocalTime is a time of day from 00:00 (inclusive) to 24:00 (exclusive). By comparing LocalTimeobjects we are ignoring the date and have no trouble with irrelevant dates in 1970 or some other time in history.
Edit:
Also is it possible to get the date and time of rangeStart and
rangeEnd in order to verify for which particular day and time we are
checking the conditions?
No, that would not make sense. Since a LocalTime is a time of day without date, there is no way to get a date out of it. But you can print the ZonedDateTime and verify its date part. And to assure yourself that the code is correct, write some unit tests.
Link: Oracle tutorial: Date Time explaining how to use java.time.
A simple approach might be to parse your time Strings to instances of LocalTime and compare them. You have to decide if the start and end time are inclusive or not...
Support some formattings because you might have to pass Strings with AM/PM or without:
public static boolean isInTimeSlot(String time, String timeSlotStart, String timeSlotEnd) {
// create a formatter that supports different formats for the String arguments
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("[hh:mm:ss a][HH:mm:ss][h a]");
// parse each argument to a LocalTime
LocalTime timeOfDay = LocalTime.parse(time, parserDtf);
LocalTime fromTime = LocalTime.parse(timeSlotStart, parserDtf);
LocalTime toTime = LocalTime.parse(timeSlotEnd, parserDtf);
// and return if the given time is in the time slot (including start and end time)
return timeOfDay.equals(fromTime) || timeOfDay.equals(toTime)
|| (timeOfDay.isAfter(fromTime) && timeOfDay.isBefore(toTime));
}
If you run it in a main like this
public static void main(String[] args) {
// provide some sample times
String[] times = { "10:31:17", "09:59:59", "6 PM", "4 AM", "06:00:01 PM" };
// provide a time slot
String from = "10 AM";
String to = "6 PM";
// check the method for each time string
for (String time : times) {
if (isInTimeSlot(time, from, to)) {
System.out.println(time + " is in the time slot at or between "
+ from + " and " + to);
} else {
System.err.println(time + " is not in the time slot at or between "
+ from + " and " + to);
}
}
}
the output will be
10:31:17 is in the time slot at or between 10 AM and 6 PM
09:59:59 is not in the time slot at or between 10 AM and 6 PM
6 PM is in the time slot at or between 10 AM and 6 PM
4 AM is not in the time slot at or between 10 AM and 6 PM
06:00:01 PM is not in the time slot at or between 10 AM and 6 PM
All I want to check if the current time from any timezone falls under the range of 10 am to 6 pm. If Yes, print "yes" else print "no".
For this, the following code will do the job.
LocalTime lt = LocalTime.now();
if( lt.isAfter( LocalTime.of( 10, 0 ) ) && lt.isBefore( LocalTime.of( 18, 0 ) ) ) System.out.println( "Yes" );
else System.out.println( "No" );
Since you have Date instances with you, you can convert them into LocalTime instances as shown below and use the same mechanism of comparison.
Date d = new Date(); //Change this to your way of creating the Date instance
LocalTime lt = LocalDateTime.ofEpochSecond( d.getTime(), 0, ZoneOffset.ofHours( 0 ) ).toLocalTime();
Hope this helps.
This question already has answers here:
Calendar returns date in wrong time zone
(5 answers)
Java: Calculate month end date based on timezone
(3 answers)
Closed 3 years ago.
Hi I noticed that Joda DateTime created using Zone is returning toDate as per Current System Date. I was expecting toDate to return as per Created DateTime. As per Joda API, it says toDate should return Date initialised with this datetime. I am using Joda 2.9.4 in my Maven. Any thoughts from Gurus out in SO
public class TestJodaError {
public static void main(String[] args) {
DateTime ldt = new DateTime();
System.out.println("Local dt: " + ldt + " toDate: " + ldt.toDate());
String tzId = "Asia/Singapore";
ZoneId zoneId = ZoneId.of(tzId);
ZonedDateTime zdt = ZonedDateTime.now(zoneId);
DateTimeZone dtZone = DateTimeZone.forID(zdt.getZone().getId());
DateTime rdt = new DateTime(dtZone);
System.out.println("Remote dt: " + rdt + " toDate: " + rdt.toDate());
}}
Results are
Local dt: 2019-05-17T11:33:30.333+05:30 toDate: Fri May 17 11:33:30 IST 2019
Remot dt: 2019-05-17T14:03:30.738+08:00 toDate: Fri May 17 11:33:30 IST 2019
Expected Results
Remot dt: 2019-05-17T14:03:30.738+08:00 toDate: Fri May 17 14:03:30 SGT 2019
As Andy mentioned, Date will not have any specific time zone info. If you want to use without Joda time and want to leverage Java 8, I provide below the code snippet.
LocalDateTime ldt = LocalDateTime.of(2019, Month.MAY, 17, 11, 30);
ZonedDateTime klDateTime = ldt.atZone(ZoneId.of("Asia/Kolkata"));
DateTimeFormatter indianFormat = DateTimeFormatter.ofPattern("dd MMM yyyy");
String output = klDateTime.format(indianFormat);
Printing a java.util.Date will always use the JVM's default time zone, because Date doesn't actually contain any time zone information.
As such, printing the result of rdt.toDate() will print in IST if ldt.toDate() also prints in IST.
I know there are lots of questions on SO about how to get Dates in Java, but I want an example using new Java 8 Date API. I also know about the JodaTime library, but I want a method without relying on external libraries.
The function needs to be compliant with these restrictions:
Prevent errors from date savetime
Inputs are two Date objects (without time, I know about LocalDateTime, but I need to do this with Date instances)
If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:
LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);
If you want literal 24 hour days, (a duration), you can use the Duration class instead:
LocalDate today = LocalDate.now()
LocalDate yesterday = today.minusDays(1);
// Duration oneDay = Duration.between(today, yesterday); // throws an exception
Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option
For more information, refer to this document.
Based on VGR's comments here is what you can use:
ChronoUnit.DAYS.between(firstDate, secondDate)
You can use until:
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
LocalDate christmas = LocalDate.of(2014, Month.DECEMBER, 25);
System.out.println("Until christmas: " + independenceDay.until(christmas));
System.out.println("Until christmas (with crono): " + independenceDay.until(christmas, ChronoUnit.DAYS));
Output:
Until christmas: P5M21D
Until christmas (with crono): 174
As mentioned in a comment, if no unit is specified until returns Period.
Snippet from the documentation:
A date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'.
This class models a quantity or amount of time in terms of years, months, and days. See Duration for the time-based equivalent to this class.
DAYS.between
You can use DAYS.between from java.time.temporal.ChronoUnit
e.g.
import java.time.temporal.ChronoUnit;
...
long totalDaysBetween(LocalDate dateBefore, LocalDate dateAfter) {
return DAYS.between(dateBefore, dateAfter);
If startDate and endDate are instance of java.util.Date
We can use the between( ) method from ChronoUnit enum:
public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) {
//..
}
ChronoUnit.DAYS count days which completed 24 hours.
import java.time.temporal.ChronoUnit;
ChronoUnit.DAYS.between(startDate.toInstant(), endDate.toInstant());
//OR
ChronoUnit.DAYS.between(Instant.ofEpochMilli(startDate.getTime()), Instant.ofEpochMilli(endDate.getTime()));
Everyone is saying to use ChronoUnit.DAYS.between but that just delegates to another method you could call yourself. So you could also do firstDate.until(secondDate, ChronoUnit.DAYS).
The docs for both actually mention both approaches and say to use whichever one is more readable.
Use the DAYS in enum java.time.temporal.ChronoUnit . Below is the Sample Code :
Output :
*Number of days between the start date : 2015-03-01 and end date : 2016-03-03 is ==> 368.
**Number of days between the start date : 2016-03-03 and end date : 2015-03-01 is ==> -368*
package com.bitiknow.date;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
/**
*
* #author pradeep
*
*/
public class LocalDateTimeTry {
public static void main(String[] args) {
// Date in String format.
String dateString = "2015-03-01";
// Converting date to Java8 Local date
LocalDate startDate = LocalDate.parse(dateString);
LocalDate endtDate = LocalDate.now();
// Range = End date - Start date
Long range = ChronoUnit.DAYS.between(startDate, endtDate);
System.out.println("Number of days between the start date : " + dateString + " and end date : " + endtDate
+ " is ==> " + range);
range = ChronoUnit.DAYS.between(endtDate, startDate);
System.out.println("Number of days between the start date : " + endtDate + " and end date : " + dateString
+ " is ==> " + range);
}
}
Get number of days before Christmas from current day , try this
System.out.println(ChronoUnit.DAYS.between(LocalDate.now(),LocalDate.of(Year.now().getValue(), Month.DECEMBER, 25)));
Here you go:
public class DemoDate {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 1 month to the current date
LocalDate date2 = today.plus(1, ChronoUnit.MONTHS);
System.out.println("Next month: " + date2);
// Put latest date 1st and old date 2nd in 'between' method to get -ve date difference
long daysNegative = ChronoUnit.DAYS.between(date2, today);
System.out.println("Days : "+daysNegative);
// Put old date 1st and new date 2nd in 'between' method to get +ve date difference
long datePositive = ChronoUnit.DAYS.between(today, date2);
System.out.println("Days : "+datePositive);
}
}
get days between two dates date is instance of java.util.Date
public static long daysBetweenTwoDates(Date dateFrom, Date dateTo) {
return DAYS.between(Instant.ofEpochMilli(dateFrom.getTime()), Instant.ofEpochMilli(dateTo.getTime()));
}
If the goal is just to get the difference in days and since the above answers mention about delegate methods would like to point out that once can also simply use -
public long daysInBetween(java.time.LocalDate startDate, java.time.LocalDate endDate) {
// Check for null values here
return endDate.toEpochDay() - startDate.toEpochDay();
}
I know this question is for Java 8, but with Java 9 you could use:
public static List<LocalDate> getDatesBetween(LocalDate startDate, LocalDate endDate) {
return startDate.datesUntil(endDate)
.collect(Collectors.toList());
}
Use the class or method that best meets your needs:
the Duration class,
Period class,
or the ChronoUnit.between method.
A Duration measures an amount of time using time-based values (seconds, nanoseconds).
A Period uses date-based values (years, months, days).
The ChronoUnit.between method is useful when you want to measure an amount of time in a single unit of time only, such as days or seconds.
https://docs.oracle.com/javase/tutorial/datetime/iso/period.html
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
LocalDate dateBefore = LocalDate.of(2020, 05, 20);
LocalDate dateAfter = LocalDate.now();
long daysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter);
long monthsBetween= ChronoUnit.MONTHS.between(dateBefore, dateAfter);
long yearsBetween= ChronoUnit.YEARS.between(dateBefore, dateAfter);
System.out.println(daysBetween);