I have a method which generates a random date and time.
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.Period;
public String getRandomFormattedDateAndTime() {
LocalDateTime date = generateRandomDateAndTimeInPast();
return formatDate(date);
}
public LocalDateTime generateRandomDateAndTimeInPast() {
return LocalDateTime.now()
.minus(Period.ofDays(
(new Random().nextInt(365 * 2))
));
}
public static String formatDate(LocalDateTime date) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT_PATTERN);
return dateTimeFormatter.format(date);
}
and the printed output is something like "2020-08-07T08:57:09Z"
However, i need to obtain the same value with time zone format 2020-08-07T10:57:09+02:00 which has the +02:00 (my local time).
I have seen several questions and pages like this, but they do not give me a clue.
I hope this is what you are looking for:
ZonedDateTime zonedDateTime = ZonedDateTime.now().minus(Period.ofDays((new Random().nextInt(365 * 2))));
System.out.println("Date Time:" + zonedDateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
Output: Date Time:2019-07-13T14:27:51.909+05:30
Note: 05:30 is my time zone (local) offset
In your example you're using the type LocalDateTime. LocalDateTime can't be formatted with timezone pattern as it doesn't contains any timezone information...
Switch to ZonedDateTime will solve your problem.
Not sure why people are involving ZonedDateTime here, but it seems to be a valid approach...
However, I want to add another one, that is the use of an OffsetDateTime.
This is an adjusted version of your method generateRandomDateAndTimeInPast:
public static OffsetDateTime generateRandomDateAndTimeInPast(int offset) {
return OffsetDateTime.now(ZoneOffset.ofHours(offset))
.minusDays(
ThreadLocalRandom.current()
.nextInt(365 * 2)
);
}
An example use could look like this, please note the implicit call to OffsetDateTime.toString() by directly System.outing the instance of OffsetDateTime. You can alter the output by calling OffsetDateTime.format(DateTimeFormatter).
public static void main(String[] args) {
OffsetDateTime odt = generateRandomDateAndTimeInPast(2);
System.out.println(odt);
}
This prints out datetimes formatted like the following (randomly generated) one:
2020-10-14T10:44:23.304+02:00
If you need a LocalDateTime (that won't contain or print any offset), you can simply get it from the OffsetDateTime like this:
LocalDateTime ldt = odt.toLocalDateTime();
A ZonedDateTime has that method, too, so if you use that or an OffsetDateTime you can always have the LocalDateTime they are based on by calling toLocalDateTime().
You have not provided the code of your method, formatDate(LocalDate). However, you have mentioned that String getRandomFormattedDateAndTime() is returning you 2020-08-07T08:57:09Z. The following method, getDateTimeInMyTz(String) provides you with what you are looking for:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(getDateTimeInMyTz("2020-08-07T08:57:09Z"));
}
public static String getDateTimeInMyTz(String strDtUtc) {
Instant instant = Instant.parse(strDtUtc);
ZoneOffset offset = ZoneId.systemDefault().getRules().getOffset(instant);
return instant.atOffset(offset).toString();
}
}
Output in my timezone which has an offset of +01:00 hours:
2020-08-07T09:57:09+01:00
Usage: Replace getDateTimeInMyTz("2020-08-07T08:57:09Z") with getDateTimeInMyTz(getRandomFormattedDateAndTime()).
If you share the code of your method, formatDate(LocalDate), I can suggest further simplification.
Learn more about java.time, the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
I want to subtract 7 days from Now, but keeping the time, so If now is
12/09/2018 at 18:30, get 05/09/2018 at 18:30...
I've tried:
public static Date subtractDays (int numDaysToSubstract) {
LocalDate now = LocalDate.now().minusDays(numDaysToSubstract);
return Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());
}
But I got 05/09/2018 at 00:00
As others have suggested, LocalDate and atStartOfDay should have been red flags based on just their name. They are the wrong type to describe a time and the wrong method to maintain the time.
It's also kind of pointless to go through LocalDateTime to then convert it to an Instant. Just use an Instant straight up
public static Date subtractDays(int numDaysToSubstract) {
return Date.from(Instant.now().minus(numDaysToSubstract, ChronoUnit.DAYS));
// or
// return Date.from(Instant.now().minus(Duration.ofDays(numDaysToSubstract)));
}
(I assume you're using java.util.Date because of compatibility with some old API.)
It’s unclear from the code in the other answers posted until now how they handle summer time (DST) and other time anomalies. And they do that differently. To make it clearer that you want 18.30 last week if time now is 18.30, no matter if a transition to or from summer time has happened in the meantime I suggest using ZonedDateTime:
System.out.println("Now: " + Instant.now());
Instant aWeekAgo = ZonedDateTime.now(ZoneId.of("Europe/Madrid"))
.minusWeeks(1)
.toInstant();
System.out.println("A week ago in Spain: " + aWeekAgo);
Since summer time in Spain hasn’t ended or begun within the last week, running the code snippet just now gave the same time of day also in UTC (which is what Instant prints):
Now: 2018-09-13T09:46:58.066957Z
A week ago in Spain: 2018-09-06T09:46:58.102680Z
I trust you to adapt the idea to your code.
Use class LocalDateTime instead of LocalDate (which doesn't contain a time component..)
You should use LocalDateTime instead of LocalDate
LocalDate is just a description of the date without time or time-zone
public static Date subtractDays (int numDaysToSubstract) {
LocalDateTime now = LocalDateTime.now().minusDays(numDaysToSubstract);
return Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
}
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Test {
public static String subtractDays (int numDaysToSubstract) {
LocalDateTime now = LocalDateTime.now().minusDays(numDaysToSubstract);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatDateTime = now.format(formatter);
return formatDateTime;
}
public static void main(String[] args){
System.out.println(subtractDays(7));
}
}
I want to get the difference of current time (Which is IST) and the time which is stored in DB(EST). In order to that I am trying to convert current time to EST before calculating the difference. But its not working. In the following approach,
local time is not getting converted to EST only. Could you please suggest me the better way to do it ?
The return type of getModifiedDate is java.sql.Timestamp and the data type
of the column is DATE
Code :
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("EST"));
cal.setTimeInMillis(System.currentTimeMillis());
cal.getTimeInMillis() - emp.getModifiedDate().getTime();
I was trying to do it using SimpleDateFormat , But I am not sure how to proceed with that approach.
If you can provide the code snippet that will be helpful
You can try java.util.TimeZone
long now = System.currentTimeMillis();
long diff = TimeZone.getTimeZone("IST").getOffset(now) - TimeZone.getTimeZone("EST").getOffset(now);
getOffset - Returns the offset of this time zone from UTC at the specified date
If you have access to Java 8, then it may be just as easy to calculate the difference between the two dates directly, rather than adjusting to a target time zone first.
You could do this using ZonedDateTime from the java.time package:
// Our timestamp
Timestamp ts = emp.getModifiedDate();
// Convert timestamp to ZonedDateTime in the correct time zone
ZonedDateTime estTime = ts.toLocalDateTime().atZone(ZoneId.of("America/New_York"));
// Could pass in ZoneId.of("Asia/Kolkata") argument to now(...), but not required
// as "now" is the same instant in all time zones.
ZonedDateTime zonedNow = ZonedDateTime.now();
// Can use other ChronoUnit values if required.
long timeDiff = ChronoUnit.MILLIS.between(zonedNow, estTime);
// Use timeDiff as required
I suggest using the java.time API of JDK 8 which simplifies this to a great extent. Consider the following example:
Timestamp t = emp.getModifiedDate();
Duration.between(t.toInstant(), ZonedDateTime.now(ZoneId.of("Asia/Kolkata")).toInstant());
The timestamp retrieved from DB has been converted to Instant which is in UTC, similarly the current time in Asia/Kolkata zone has been converted to Instant and the Duration between the two has been calculated.You can retrieve the required information from the duration.
You can find it using java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenience methods were introduced.
import java.time.Duration;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(formatDuration(diffBetweenTimeZones("Asia/Kolkata", "America/New_York")));
System.out.println(formatDuration(diffBetweenTimeZones("America/New_York", "Asia/Kolkata")));
// You can use the returned value to get the ZoneOffset which you can use for
// other processing e.g.
ZoneOffset offset = ZoneOffset.of(formatDuration(diffBetweenTimeZones("Asia/Kolkata", "America/New_York")));
System.out.println(offset);
System.out.println(OffsetDateTime.now(offset));
}
static Duration diffBetweenTimeZones(String tz1, String tz2) {
LocalDate today = LocalDate.now();
return Duration.between(today.atStartOfDay(ZoneId.of(tz1)), today.atStartOfDay(ZoneId.of(tz2)));
}
static String formatDuration(Duration duration) {
long hours = duration.toHours();
long minutes = duration.toMinutes() % 60;
String symbol = hours < 0 || minutes < 0 ? "-" : "+";
return String.format(symbol + "%02d:%02d", Math.abs(hours), Math.abs(minutes));
// ####################################Java-9####################################
// return String.format(symbol + "%02d:%02d", Math.abs(duration.toHoursPart()),
// Math.abs(duration.toMinutesPart()));
// ####################################Java-9####################################
}
}
Output:
+09:30
-09:30
+09:30
2021-03-24T19:52:29.474858+09:30
Learn more about the modern date-time API from Trail: Date Time.
Note that the java.util date-time API is outdated and error-prone. It is recommended to stop using it completely and switch to the modern date-time API*.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
TimeZone has two methods getRawOffet and getOffset that retrieves the offset of the time zone to UTC in milliseconds. The second one is adjusted for Daylight Saving Time and request the date to check if it is in effect.
TimeZone current = TimeZone.getDefault();
TimeZone db = TimeZone.getTimeZone("US/Eastern"); // or "EST5EDT", or "America/New_York"
System.out.printf("DB: %s Current: %s\n", db, current);
System.out.printf("Raw: %.1f h\n", (db.getRawOffset() - current.getRawOffset())/3_600_000D);
final long now = System.currentTimeMillis();
System.out.printf("DST: %.1f h\n", (db.getOffset(now) - current.getOffset(now))/3_600_000D);
I want to find the difference between two Calendar objects in number of days if there is date change like If clock ticked from 23:59-0:00 there should be a day difference.
i wrote this
public static int daysBetween(Calendar startDate, Calendar endDate) {
return Math.abs(startDate.get(Calendar.DAY_OF_MONTH)-endDate.get(Calendar.DAY_OF_MONTH));
}
but its not working as it only gives difference between days if there is month difference its worthless.
Try the following approach:
public static long daysBetween(Calendar startDate, Calendar endDate) {
long end = endDate.getTimeInMillis();
long start = startDate.getTimeInMillis();
return TimeUnit.MILLISECONDS.toDays(Math.abs(end - start));
}
In Java 8 and later, we could simply use the java.time classes.
hoursBetween = ChronoUnit.HOURS.between(calendarObj.toInstant(), calendarObj.toInstant());
daysBetween = ChronoUnit.DAYS.between(calendarObj.toInstant(), calendarObj.toInstant());
This function computes the number of days between two Calendars as the number of calendar days of the month that are between them, which is what the OP wanted. The calculation is performed by counting how many multiples of 86,400,000 milliseconds are between the calendars after both have been set to midnight of their respective days.
For example, my function will compute 1 day's difference between a Calendar on January 1, 11:59PM and January 2, 12:01AM.
import java.util.concurrent.TimeUnit;
/**
* Compute the number of calendar days between two Calendar objects.
* The desired value is the number of days of the month between the
* two Calendars, not the number of milliseconds' worth of days.
* #param startCal The earlier calendar
* #param endCal The later calendar
* #return the number of calendar days of the month between startCal and endCal
*/
public static long calendarDaysBetween(Calendar startCal, Calendar endCal) {
// Create copies so we don't update the original calendars.
Calendar start = Calendar.getInstance();
start.setTimeZone(startCal.getTimeZone());
start.setTimeInMillis(startCal.getTimeInMillis());
Calendar end = Calendar.getInstance();
end.setTimeZone(endCal.getTimeZone());
end.setTimeInMillis(endCal.getTimeInMillis());
// Set the copies to be at midnight, but keep the day information.
start.set(Calendar.HOUR_OF_DAY, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MILLISECOND, 0);
end.set(Calendar.HOUR_OF_DAY, 0);
end.set(Calendar.MINUTE, 0);
end.set(Calendar.SECOND, 0);
end.set(Calendar.MILLISECOND, 0);
// At this point, each calendar is set to midnight on
// their respective days. Now use TimeUnit.MILLISECONDS to
// compute the number of full days between the two of them.
return TimeUnit.MILLISECONDS.toDays(
Math.abs(end.getTimeInMillis() - start.getTimeInMillis()));
}
Extension to #JK1 great answer :
public static long daysBetween(Calendar startDate, Calendar endDate) {
//Make sure we don't change the parameter passed
Calendar newStart = Calendar.getInstance();
newStart.setTimeInMillis(startDate.getTimeInMillis());
newStart.set(Calendar.HOUR_OF_DAY, 0);
newStart.set(Calendar.MINUTE, 0);
newStart.set(Calendar.SECOND, 0);
newStart.set(Calendar.MILLISECOND, 0);
Calendar newEnd = Calendar.getInstance();
newEnd.setTimeInMillis(endDate.getTimeInMillis());
newEnd.set(Calendar.HOUR_OF_DAY, 0);
newEnd.set(Calendar.MINUTE, 0);
newEnd.set(Calendar.SECOND, 0);
newEnd.set(Calendar.MILLISECOND, 0);
long end = newEnd.getTimeInMillis();
long start = newStart.getTimeInMillis();
return TimeUnit.MILLISECONDS.toDays(Math.abs(end - start));
}
UPDATE The Joda-Time project, now in maintenance mode, advises migration to the java.time classes. See the Answer by Anees A for the calculation of elapsed hours, and see my new Answer for using java.time to calculate elapsed days with respect for the calendar.
Joda-Time
The old java.util.Date/.Calendar classes are notoriously troublesome and should be avoided.
Instead use the Joda-Time library. Unless you have Java 8 technology in which case use its successor, the built-in java.time framework (not in Android as of 2015).
Since you only care about "days" defined as dates (not 24-hour periods), let's focus on dates. Joda-Time offers the class LocalDate to represent a date-only value without time-of-day nor time zone.
While lacking a time zone, note that time zone is crucial in determining a date such as "today". A new day dawns earlier to the east than to the west. So the date is not the same around the world at one moment, the date depends on your time zone.
DateTimeZone zone = DateTimeZone.forID ( "America/Montreal" );
LocalDate today = LocalDate.now ( zone );
Let's count the number of days until next week, which should of course be seven.
LocalDate weekLater = today.plusWeeks ( 1 );
int elapsed = Days.daysBetween ( today , weekLater ).getDays ();
The getDays on the end extracts a plain int number from the Days object returned by daysBetween.
Dump to console.
System.out.println ( "today: " + today + " to weekLater: " + weekLater + " is days: " + days );
today: 2015-12-22 to weekLater: 2015-12-29 is days: 7
You have Calendar objects. We need to convert them to Joda-Time objects. Internally the Calendar objects have a long integer tracking the number of milliseconds since the epoch of first moment of 1970 in UTC. We can extract that number, and feed it to Joda-Time. We also need to assign the desired time zone by which we intend to determine a date.
long startMillis = myStartCalendar.getTimeInMillis();
DateTime startDateTime = new DateTime( startMillis , zone );
long stopMillis = myStopCalendar.getTimeInMillis();
DateTime stopDateTime = new DateTime( stopMillis , zone );
Convert from DateTime objects to LocalDate.
LocalDate start = startDateTime.toLocalDate();
LocalDate stop = stopDateTime.toLocalDate();
Now do the same elapsed calculation we saw earlier.
int elapsed = Days.daysBetween ( start , stop ).getDays ();
Here's my solution using good old Calendar objects:
public static int daysApart(Calendar d0,Calendar d1)
{
int days=d0.get(Calendar.DAY_OF_YEAR)-d1.get(Calendar.DAY_OF_YEAR);
Calendar d1p=Calendar.getInstance();
d1p.setTime(d1.getTime());
for (;d1p.get(Calendar.YEAR)<d0.get(Calendar.YEAR);d1p.add(Calendar.YEAR,1))
{
days+=d1p.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return days;
}
This assumes d0 is later than d1. If that's not guaranteed, you could always test and swap them.
Basic principle is to take the difference between the day of the year of each. If they're in the same year, that would be it.
But they might be different years. So I loop through all the years between them, adding the number of days in a year. Note that getActualMaximum returns 366 in leap years and 365 in non-leap years. That's why we need a loop, you can't just multiply the difference between the years by 365 because there might be a leap year in there. (My first draft used getMaximum, but that doesn't work because it returns 366 regardless of the year. getMaximum is the maximum for ANY year, not this particular year.)
As this code makes no assumptions about the number of hours in a day, it is not fooled by daylight savings time.
tl;dr
java.time.temporal.ChronoUnit // The java.time classes are built into Java 8+ and Android 26+. For earlier Android, get must of the functionality by using the latest tooling with "API desugaring".
.DAYS // A pre-defined enum object.
.between(
( (GregorianCalendar) startCal ) // Cast from the more abstract `Calendar` to the more concrete `GregorianCalendar`.
.toZonedDateTime() // Convert from legacy class to modern class. Returns a `ZonedDateTime` object.
.toLocalDate() // Extract just the date, to get the Question's desired whole-days count, ignoring fractional days. Returns a `LocalDate` object.
,
( (GregorianCalendar) endCal )
.toZonedDateTime()
.toLocalDate()
) // Returns a number of days elapsed between our pair of `LocalDate` objects.
java.time
The Answer by Mohamed Anees A is correct for hours but wrong for days. Counting days requires a time zone. That other Answer uses the Instant which is a moment in UTC, always in UTC. So you are not getting the correct number of calendar days elapsed.
To count days by the calendar, convert your legacy Calendar to a ZonedDateTime, then feed to ChronoUnit.DAYS.between.
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 during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.
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 ) ; // Capture the current date as seen through the wall-clock time used by the people of a certain region (a time zone).
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Convert from GregorianCalendar to ZonedDateTime
The terrible GregorianCalendar is likely the concrete class behind your Calendar. If so, convert from that legacy class to the modern class, ZonedDateTime.
GregorianCalendar gc = null ; // Legacy class representing a moment in a time zone. Avoid this class as it is terribly designed.
if( myCal instanceof GregorianCalendar ) { // See if your `Calendar` is backed by a `GregorianCalendar` class.
gc = (GregorianCalendar) myCal ; // Cast from the more general class to the concrete class.
ZonedDateTime zdt = gc.toZonedDateTime() ; // Convert from legacy class to modern class.
}
The resulting ZonedDateTime object carries a ZoneId object for the time zone. With that zone in place, you can then calculate elapsed calendar days.
Calculate elapsed days
To calculate the elapsed time in terms of years-months-days, use Period class.
Period p = Period.between( zdtStart , zdtStop ) ;
If you want total number of days as the elapsed time, use ChronoUnit.
long days = ChronoUnit.DAYS.between( zdtStart , zdtStop ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I have the similar (not exact same) approach given above by https://stackoverflow.com/a/31800947/3845798.
And have written test cases around the api, for me it failed if I passed
8th march 2017 - as the start date and 8th apr 2017 as the end date.
There are few dates where you will see the difference by 1day.
Therefore, I have kind of made some small changes to my api and my current api now looks something like this
public long getDays(long currentTime, long endDateTime) {
Calendar endDateCalendar;
Calendar currentDayCalendar;
//expiration day
endDateCalendar = Calendar.getInstance(TimeZone.getTimeZone("EST"));
endDateCalendar.setTimeInMillis(endDateTime);
endDateCalendar.set(Calendar.MILLISECOND, 0);
endDateCalendar.set(Calendar.MINUTE, 0);
endDateCalendar.set(Calendar.HOUR, 0);
endDateCalendar.set(Calendar.HOUR_OF_DAY, 0);
//current day
currentDayCalendar = Calendar.getInstance(TimeZone.getTimeZone("EST"));
currentDayCalendar.setTimeInMillis(currentTime);
currentDayCalendar.set(Calendar.MILLISECOND, 0);
currentDayCalendar.set(Calendar.MINUTE, 0);
currentDayCalendar.set(Calendar.HOUR,0);
currentDayCalendar.set(Calendar.HOUR_OF_DAY, 0);
long remainingDays = (long)Math.ceil((float) (endDateCalendar.getTimeInMillis() - currentDayCalendar.getTimeInMillis()) / (24 * 60 * 60 * 1000));
return remainingDays;}
I am not using TimeUnit.MILLISECONDS.toDays that were causing me some issues.
Kotlin solution, purely relies on Calendar. At the end gives exact number of days difference.
Inspired by #Jk1
private fun daysBetween(startDate: Calendar, endDate: Calendar): Long {
val start = Calendar.getInstance().apply {
timeInMillis = 0
set(Calendar.DAY_OF_YEAR, startDate.get(Calendar.DAY_OF_YEAR))
set(Calendar.YEAR, startDate.get(Calendar.YEAR))
}.timeInMillis
val end = Calendar.getInstance().apply {
timeInMillis = 0
set(Calendar.DAY_OF_YEAR, endDate.get(Calendar.DAY_OF_YEAR))
set(Calendar.YEAR, endDate.get(Calendar.YEAR))
}.timeInMillis
val differenceMillis = end - start
return TimeUnit.MILLISECONDS.toDays(differenceMillis)
}
If your project doesn't support new Java 8 classes (as selected answer), you can add this method to calculate the days without being influenced by timezones or other facts.
It is not as fast (greater time complexity) as other methods but it's reliable, anyways date comparisons are rarely larger than hundreds or thousands of years.
(Kotlin)
/**
* Returns the number of DAYS between two dates. Days are counted as calendar days
* so that tomorrow (from today date reference) will be 1 , the day after 2 and so on
* independent on the hour of the day.
*
* #param date - reference date, normally Today
* #param selectedDate - date on the future
*/
fun getDaysBetween(date: Date, selectedDate: Date): Int {
val d = initCalendar(date)
val s = initCalendar(selectedDate)
val yd = d.get(Calendar.YEAR)
val ys = s.get(Calendar.YEAR)
if (ys == yd) {
return s.get(Calendar.DAY_OF_YEAR) - d.get(Calendar.DAY_OF_YEAR)
}
//greater year
if (ys > yd) {
val endOfYear = Calendar.getInstance()
endOfYear.set(yd, Calendar.DECEMBER, 31)
var daysToFinish = endOfYear.get(Calendar.DAY_OF_YEAR) - d.get(Calendar.DAY_OF_YEAR)
while (endOfYear.get(Calendar.YEAR) < s.get(Calendar.YEAR)-1) {
endOfYear.add(Calendar.YEAR, 1)
daysToFinish += endOfYear.get(Calendar.DAY_OF_YEAR)
}
return daysToFinish + s.get(Calendar.DAY_OF_YEAR)
}
//past year
else {
val endOfYear = Calendar.getInstance()
endOfYear.set(ys, Calendar.DECEMBER, 31)
var daysToFinish = endOfYear.get(Calendar.DAY_OF_YEAR) - s.get(Calendar.DAY_OF_YEAR)
while (endOfYear.get(Calendar.YEAR) < d.get(Calendar.YEAR)-1) {
endOfYear.add(Calendar.YEAR, 1)
daysToFinish += endOfYear.get(Calendar.DAY_OF_YEAR)
}
return daysToFinish + d.get(Calendar.DAY_OF_YEAR)
}
}
Unit Tests, you can improve them I didn't need the negative days so I didn't test that as much:
#Test
fun `Test days between on today and following days`() {
val future = Calendar.getInstance()
calendar.set(2019, Calendar.AUGUST, 26)
future.set(2019, Calendar.AUGUST, 26)
Assert.assertEquals(0, manager.getDaysBetween(calendar.time, future.time))
future.set(2019, Calendar.AUGUST, 27)
Assert.assertEquals(1, manager.getDaysBetween(calendar.time, future.time))
future.set(2019, Calendar.SEPTEMBER, 1)
Assert.assertEquals(6, manager.getDaysBetween(calendar.time, future.time))
future.set(2020, Calendar.AUGUST, 26)
Assert.assertEquals(366, manager.getDaysBetween(calendar.time, future.time)) //leap year
future.set(2022, Calendar.AUGUST, 26)
Assert.assertEquals(1096, manager.getDaysBetween(calendar.time, future.time))
calendar.set(2019, Calendar.DECEMBER, 31)
future.set(2020, Calendar.JANUARY, 1)
Assert.assertEquals(1, manager.getDaysBetween(calendar.time, future.time))
}
#Test
fun `Test days between on previous days`() {
val future = Calendar.getInstance()
calendar.set(2019, Calendar.AUGUST, 26)
future.set(2019,Calendar.AUGUST,25)
Assert.assertEquals(-1, manager.getDaysBetween(calendar.time, future.time))
}
#Test
fun `Test days between hour doesn't matter`() {
val future = Calendar.getInstance()
calendar.set(2019, Calendar.AUGUST, 26,9,31,15)
future.set(2019,Calendar.AUGUST,28, 7,0,0)
Assert.assertEquals(2, manager.getDaysBetween(calendar.time, future.time))
future.set(2019,Calendar.AUGUST,28, 9,31,15)
Assert.assertEquals(2, manager.getDaysBetween(calendar.time, future.time))
future.set(2019,Calendar.AUGUST,28, 23,59,59)
Assert.assertEquals(2, manager.getDaysBetween(calendar.time, future.time))
}
#Test
fun `Test days between with time saving change`() {
val future = Calendar.getInstance()
calendar.set(2019, Calendar.OCTOBER, 28)
future.set(2019, Calendar.OCTOBER,29)
Assert.assertEquals(1, manager.getDaysBetween(calendar.time, future.time))
future.set(2019, Calendar.OCTOBER,30)
Assert.assertEquals(2, manager.getDaysBetween(calendar.time, future.time))
}
public int getIntervalDays(Calendar c1,Calendar c2){
Calendar first = cleanTimePart(c1);
Calendar second = cleanTimePart(c2);
Long intervalDays = (first.getTimeInMillis() - second.getTimeInMillis())/(1000*3600*24);
return intervalDays.intValue();
}
private Calendar cleanTimePart(Calendar dateTime){
Calendar newDateTime = (Calendar)dateTime.clone();
newDateTime.set(Calendar.HOUR_OF_DAY,0);
newDateTime.set(Calendar.MINUTE,0);
newDateTime.set(Calendar.SECOND,0);
newDateTime.set(Calendar.MILLISECOND,0);
return newDateTime;
}
Calendar day1 = Calendar.getInstance(); Calendar day2 = Calendar.getInstance(); int diff = day1.get(Calendar.DAY_OF_YEAR)
- day2.get(Calendar.DAY_OF_YEAR);
I need to determine the current year in Java as an integer. I could just use java.util.Date(), but it is deprecated.
For Java 8 onwards:
int year = Year.now().getValue();
For older version of Java:
int year = Calendar.getInstance().get(Calendar.YEAR);
Using Java 8's time API (assuming you are happy to get the year in your system's default time zone), you could use the Year::now method:
int year = Year.now().getValue();
This simplest (using Calendar, sorry) is:
int year = Calendar.getInstance().get(Calendar.YEAR);
There is also the new Date and Time API JSR, as well as Joda Time
You can also use 2 methods from java.time.YearMonth( Since Java 8 ):
import java.time.YearMonth;
...
int year = YearMonth.now().getYear();
int month = YearMonth.now().getMonthValue();
tl;dr
ZonedDateTime.now( ZoneId.of( "Africa/Casablanca" ) )
.getYear()
Time Zone
The answer by Raffi Khatchadourian wisely shows how to use the new java.time package in Java 8. But that answer fails to address the critical issue of time zone in determining a date.
int year = LocalDate.now().getYear();
That code depends on the JVM's current default time zone. The default zone is used in determining what today’s date is. Remember, for example, that in the moment after midnight in Paris the date in Montréal is still 'yesterday'.
So your results may vary by what machine it runs on, a user/admin changing the host OS time zone, or any Java code at any moment changing the JVM's current default. Better to specify the time zone.
By the way, always use proper time zone names as defined by the IANA. Never use the 3-4 letter codes that are neither standardized nor unique.
java.time
Example in java.time of Java 8.
int year = ZonedDateTime.now( ZoneId.of( "Africa/Casablanca" ) ).getYear() ;
Joda-Time
Some idea as above, but using the Joda-Time 2.7 library.
int year = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).getYear() ;
Incrementing/Decrementing Year
If your goal is to jump a year at a time, no need to extract the year number. Both Joda-Time and java.time have methods for adding/subtracting a year at a time. And those methods are smart, handling Daylight Saving Time and other anomalies.
Example in java.time.
ZonedDateTime zdt =
ZonedDateTime
.now( ZoneId.of( "Africa/Casablanca" ) )
.minusYears( 1 )
;
Example in Joda-Time 2.7.
DateTime oneYearAgo = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).minusYears( 1 ) ;
The easiest way is to get the year from Calendar.
// year is stored as a static member
int year = Calendar.getInstance().get(Calendar.YEAR);
If you want the year of any date object, I used the following method:
public static int getYearFromDate(Date date) {
int result = -1;
if (date != null) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
result = cal.get(Calendar.YEAR);
}
return result;
}
Use the following code for java 8 :
LocalDate localDate = LocalDate.now();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int date = localDate.getDayOfMonth();
You can also use Java 8's LocalDate:
import java.time.LocalDate;
//...
int year = LocalDate.now().getYear();
If your application is making heavy use of Date and Calendar objects, you really should use Joda Time, because java.util.Date is mutable. java.util.Calendar has performance problems when its fields get updated, and is clunky for datetime arithmetic.
As some people answered above:
If you want to use the variable later, better use:
int year;
year = Calendar.getInstance().get(Calendar.YEAR);
If you need the year for just a condition you better use:
Calendar.getInstance().get(Calendar.YEAR)
For example using it in a do while that checks introduced year is not less than the current year-200 or more than the current year (Could be birth year):
import java.util.Calendar;
import java.util.Scanner;
public static void main (String[] args){
Scanner scannernumber = new Scanner(System.in);
int year;
/*Checks that the year is not higher than the current year, and not less than the current year - 200 years.*/
do{
System.out.print("Year (Between "+((Calendar.getInstance().get(Calendar.YEAR))-200)+" and "+Calendar.getInstance().get(Calendar.YEAR)+") : ");
year = scannernumber.nextInt();
}while(year < ((Calendar.getInstance().get(Calendar.YEAR))-200) || year > Calendar.getInstance().get(Calendar.YEAR));
}
In my case none of the above is worked. So After trying lot of solutions i found below one and it worked for me
import java.util.Scanner;
import java.util.Date;
public class Practice
{
public static void main(String[] args)
{
Date d=new Date();
int year=d.getYear();
int currentYear=year+1900;
System.out.println(currentYear);
}
}
I may add that a simple way to get the current year as an integer is importing
java.time.LocalDate and, then:
import java.time.LocalDate;
int yourVariable = LocalDate.now().getYear()
Hope this helps!
You can do the whole thing using Integer math without needing to instantiate a calendar:
return (System.currentTimeMillis()/1000/3600/24/365.25 +1970);
May be off for an hour or two at new year but I don't get the impression that is an issue?
In Java version 8+ can (advised to) use java.time library. ISO 8601 sets standard way to write dates: YYYY-MM-DD and java.time.Instant uses it, so (for UTC):
import java.time.Instant;
int myYear = Integer.parseInt(Instant.now().toString().substring(0,4));
P.S. just in case (and shorted for getting String, not int), using Calendar looks better and can be made zone-aware.
I use special functions in my library to work with days/month/year ints -
int[] int_dmy( long timestamp ) // remember month is [0..11] !!!
{
Calendar cal = new GregorianCalendar(); cal.setTimeInMillis( timestamp );
return new int[] {
cal.get( Calendar.DATE ), cal.get( Calendar.MONTH ), cal.get( Calendar.YEAR )
};
};
int[] int_dmy( Date d ) {
...
}