Pulling time from api/json and comparing it to a set date - java

System.out.println(json.toString());
System.out.println(json.get("date"));
returns time in epoch time such as: 1609642292
> Task :Program:DateUtils.main()
{"date":1609642292}
1609642292
This is what I'm using to pull the date from the API
import java.io.InputStreamReader;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
public class DateUtils
{
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
// InputStream is = new URL(url).openStream();
try (var is = new URL(url).openStream()) {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("https://Time.xyz/api/date"); //Don't want to post real API
System.out.println(json.toString());
System.out.println(json.get("date"));
}
}
In my other java file I'm trying to do something like
Calendar expiry = Calendar.getInstance();
expiry.set(2021,1,31,0,0) //When my program expires:year, month, date, hour, min
Calendar now = DateUtils.getAtomicTime();
//where DateUtils.getAtomicTime comes from this class that pulls current time from the National Institute of Standards and Technology
//https://www.rgagnon.com/javadetails/java-0589.html
if (now.after(expiry)) {
shutdown()
}else{
startProgram()
}
}
How can I change
Calendar now - DateUtils.getatomicTime() to this new API
My problems:
I don't know how to use what I have to check for the time and refer to it.
Like it prints the time properly, but now how do I use that println jsontostring and then use that to add it to that code slightly above to compare my Set Expiration Date with API date.
Please give me some advice. Thank you.

It appears that the goal is to use the epoch time in the date element of the server response and call shutdown if that is earlier than the current time.
Instead of creating Calendar instances, I would compare the current epoch time to the value in the HTTP response.
if (DateUtils.readJsonFromUrl("https://Time.xyz/api/date").get("date") * 1000 < System.currentTimeMillis()) {
shutdown();
} else {
startProgram();
}

tl;dr
Your Question is not clear. But it seems you want to compare some moment represented as a textual number of whole seconds since 1970-01-01T00:00Z to some number of calendar days past the current moment as captured from a remote time server using some library you’ve not explained.
boolean isFurtherOutIntoTheFuture =
Instant // Represent a moment, a point on the timeline, resolving to nanoseconds, as seen in UTC.
.ofEpochSecond( // Interpret a number as a count of whole seconds since the epoch reference point of 1970-01-01T00:00Z.
Long.parseLong( "1609642292" ) // Parse text as a number, a 64-bit `long`.
) // Returns a `Instant`.
.isAfter( // Compare one `Instant` object to another.
DateUtils // Some mysterious library that fetches current moment from a remote time server.
.getAtomicTime() // Returns a `java.until.Date` object (apparently – not explained in Question).
.toInstant() // Convert from legacy class to its modern replacement.
.atZone( // Adjust from UTC to some time zone. Same moment, different wall-clock time.
ZoneId.of( "Africa/Tunis" ) // Whatever time zone by which you want to add some number of calendar days.
) // Returns a `ZonedDateTime` object.
.plusDays( x ) // Add some number of calendar days (*not* necessarily 24-hours long). Returns a new `ZonedDateTime` object with values based on the original.
.toInstant() // Adjust from some time zone to UTC (an offset-from-UTC of zero hours, minutes, and seconds).
) // Returns a `boolean`.
;
Details
Never use Calendar. That terrible class was supplanted years ago by the modern java.time classes.
Convert your epoch seconds to Instant by calling Instant.ofEpochSecond. Pass a long parsed from your textual input.
Apparently a call to the DateUtils.getAtomicTime, of some library you neglected to mention, results in Java.until.Date. Convert that terrible legacy class to its modern replacement, java.time.Instant. Notice the new to… and from… conversion methods added to the old legacy classes.
Instant now = DateUtils.getAtomicTime().toInstant() ;
Compare to current moment.
boolean isInTheFuture = someInstant.isAfter( now ) ;
You commented about “x amount of days”. Did you mean calendars days or generic chunks of 24-hours? If the latter:
Instant later = myInstant.plus( Duration.ofDays( x ) ) ;
If you meant calendar days, apply a time zone.
ZoneId z = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
ZonedDateTime later = zdt.plusDays( x ) ;
Instant laterInUtc = later.toInstant() ;
All of this has been covered many many many times already on Stack Overflow. Search to learn more.

The answer by Basil Bourque guides you in the right direction. This answer is focused on what code you should write.
The class, Instant serves as the bridge between the legacy date-time API and the modern date-time API. Convert the java.util.Calendar object (which you are getting from json.get("date")) to Instant using Calendar#toInstant.
For expiry date, you can create an Instant object using the OffsetDateTime object set with ZoneOffset.UTC.
Finally, you can compare these two objects of Instant using Instant#isAfter.
Based on the explanation given above, you need to write the following code:
JSONObject json = readJsonFromUrl("https://Time.xyz/api/date");
Calendar now = json.get("date");
Instant instantNow = now.toInstant();
Instant expiry = OffsetDateTime.of(LocalDateTime.of(2021, 1, 31, 0, 0), ZoneOffset.UTC).toInstant();
if (instantNow.isAfter(expiry)) {
shutdown();
} else {
startProgram();
}
Learn about the modern date-time API from Trail: Date Time.
Note that the date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them 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.

Related

How to generate a random time between two times say 4PM and 2AM?

I have tried using -
int startSeconds = restaurant.openingTime.toSecondOfDay();
int endSeconds = restaurant.closingTime.toSecondOfDay();
LocalTime timeBetweenOpenClose = LocalTime.ofSecondOfDay(ThreadLocalRandom.current().nextInt(startSeconds, endSeconds));
But this usually runs into an error as in nextInt(origin, bounds), origin can't be less than bounds which will happen if my openingTime is 16:00:00 and closingTime is 02:00:00.
You can add the seconds of one day(24*60*60) when startSeconds is greater than endSeconds to represent the next day's second and after getting a random number modulo it by the seconds of one day to convert it into LocalTime by a valid second value.
int secondsInDay = (int)Duration.ofDays(1).getSeconds();
if(startSeconds > endSeconds){
endSeconds += secondsInDay;
}
LocalTime timeBetweenOpenClose = LocalTime.ofSecondOfDay(
ThreadLocalRandom.current().nextInt(startSeconds, endSeconds) % secondsInDay);
We cannot know how much time will elapse between 4 PM and 2 AM without applying a date and time zone. Therefore, we will solve it using ZonedDateTime.
The first step will be: obtain a ZonedDateTime by calling LocalDate#atStartOfDay
ZoneId zoneId = ZoneId.systemDefault();
LocalDate.now().atStartOfDay(zoneId);
Next, use ZonedDateTime#with to get a ZonedDateTime with the specified time.
Now, you can derive an Instant from a ZonedDateTime using ZonedDateTime#toInstant.
Once you have the start and end Instants derived this way, you can use ThreadLocalRandom.current().nextLong to generate a long value in the range of the start and the end Instants and use the obtained value to get the required Instant.
Finally, you can derive a ZonedDateTime from this Instant using Instant#atZone and then get the required time using ZonedDateTime#toLocalTime.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.concurrent.ThreadLocalRandom;
public class Main {
public static void main(String[] args) {
// Change it as per the applicable timezone e.g. ZoneId.of("Europe/London")
ZoneId zoneId = ZoneId.systemDefault();
LocalDate today = LocalDate.now();
ZonedDateTime zdtStart = today.atStartOfDay(zoneId)
.with(LocalTime.of(16, 0));
ZonedDateTime zdtEnd = today.plusDays(1)
.atStartOfDay(zoneId)
.with(LocalTime.of(2, 0));
ZonedDateTime zdtResult =
Instant.ofEpochMilli(
ThreadLocalRandom
.current()
.nextLong(
zdtStart.toInstant().toEpochMilli(),
zdtEnd.toInstant().toEpochMilli()
)
).atZone(zoneId);
LocalTime time = zdtResult.toLocalTime();
System.out.println(time);
}
}
Learn more about the modern date-time API from Trail: Date Time.
ONLINE DEMO printing 100 random times.

How to get UTC date of a date?

Below is a Java POJO in my application:
public class Appointment {
private Date appointmentStartDatetime;
private String timezone;
//...
}
Example values for these 2 properties are:
2021-10-06 05:30:00
"America/New_York"
appointmentStartDatetime represents the appointment start time in its declared timezone - i.e. the appointment starts at 5.30 in New York.
I want to convert this to a UTC date.
Is the below correct in order to do so?
public static Date dateToUTC(Date date, String timezoneId){
Calendar calendar = Calendar.getInstance();
TimeZone timeZone = TimeZone.getTimeZone(timezoneId);
calendar.setTimeZone(timeZone);
return new Date(date.getTime() - calendar.getTimeZone().getOffset(date.getTime()));
}
The method would be called as follows:
Date utcDate = dateToUTC(appointment.getEventStartDatetime(),appointment.getTimezone())
java.time
To avoid confusion use ZonedDateTime from java.time, the modern Java date and time API, for your date and time with time zone.
public class Appointment {
private ZonedDateTime appointmentStartDateTime;
// Constructor, etc.
public Instant getUtcDateTime() {
return appointmentStartDateTime.toInstant();
}
}
Try it out:
Appointment myAppointment = new Appointment(
ZonedDateTime.of(2021, 1, 10, 5, 30, 0, 0,
ZoneId.of("America/New_York")));
System.out.println(myAppointment.getUtcDateTime());
Output is:
2021-01-10T10:30:00Z
A ZonedDateTime is a date and time in a time zone. So you need only this one field instead of the two you had, appointmentStartDatetime and timezone. An Instant is a point in time independent of time zone. It prints in UTC, denoted by the trailing Z of the output above. And the conversion from ZonedDateTime to Instant is a matter of a simple method call.
Link
Oracle tutorial: Date Time explaining how to use java.time.
The java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). When you print an object of java.util.Date, its toString method returns the date-time in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat and obtain the formatted string from it.
Note that the date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them 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.
Using the modern date-time API:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
class Appointment {
private LocalDateTime appointmentStartDatetime;
private String timezone;
public Appointment(LocalDateTime appointmentStartDatetime, String timezone) {
this.appointmentStartDatetime = appointmentStartDatetime;
this.timezone = timezone;
}
public LocalDateTime getAppointmentInLocalDateTime() {
return appointmentStartDatetime;
}
public Instant getAppointmentInUTC() {
return appointmentStartDatetime.toInstant(ZoneOffset.UTC);
}
public ZonedDateTime getAppointmentInZonedDateTime() {
return appointmentStartDatetime.atZone(ZoneId.of(timezone));
}
public ZonedDateTime getAppointmentInZdtAnotherTimeZone(String timezone) {
return getAppointmentInZonedDateTime().withZoneSameInstant(ZoneId.of(timezone));
}
// ...
}
public class Main {
public static void main(String[] args) {
Appointment appointment = new Appointment(
LocalDateTime.of(LocalDate.of(2020, Month.FEBRUARY, 15), LocalTime.of(10, 30)), "America/New_York");
System.out.println(appointment.getAppointmentInLocalDateTime());
System.out.println(appointment.getAppointmentInUTC());
System.out.println(appointment.getAppointmentInZonedDateTime());
System.out.println(appointment.getAppointmentInZdtAnotherTimeZone("Asia/Calcutta"));
}
}
Output:
2020-02-15T10:30
2020-02-15T10:30:00Z
2020-02-15T10:30-05:00[America/New_York]
2020-02-15T21:00+05:30[Asia/Calcutta]
An Instant represents an instantaneous point on the time-line.
A ZonedDateTime holds state equivalent to three separate objects, a LocalDateTime, a ZoneId and the resolved ZoneOffset. The function, ZonedDateTime#withZoneSameInstant returns a copy of this date-time with a different time-zone, retaining the instant.
Given below is an overview of the Java SE 8 date-time types:
Learn more about the modern date-time API from Trail: Date Time.

What is the jconsole time format?

I have monitored my java program using jconsole recently. I saved CPU usage data as a csv file. This is what I've got:
Time,CPU Usage
43690.008014,1,8
43690.008060,0,1
43690.008106,0,1
43690.008153,0,1
43690.008199,0,1
43690.008245,0,1
The CPU Usage column is clear, but I cannot say the same thing about the Time column. What is 43690.008014? How can I parse it into Date? I haven't seen anything like this in my life.
The duration recorded in the CSV file is the number of days since 1899-12-311. In order to get the current date, you can add this duration to LocalDate.of(1899, 12, 30).atStartOfDay().atOffset(ZoneOffset.UTC). I recommend you use java.time.Duration which is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. The function, Duration#ofNanos gives you a Duration representing the specified number of nanoseconds. The reason why I am recommending you to use this function despite the fact that there is already a function, Duration#ofDays is that these functions take a long value as the argument and if you cast the duration in your log file (e.g. 43690.008014) to long, its fractional part will be lost giving you an incorrect result.
Therefore, convert these days to nanoseconds, get Duration from the resulting nanoseconds and add the same to LocalDate.of(1899, 12, 30).atStartOfDay().atOffset(ZoneOffset.UTC) to get the current date and time in UTC.
Demo:
import java.time.Duration;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
OffsetDateTime startDateTime = LocalDate.of(1899, 12, 30).atStartOfDay().atOffset(ZoneOffset.UTC);
OffsetDateTime current = startDateTime
.plus(Duration.ofNanos((long) (43690.008014 * 24 * 60 * 60 * 1000_000_000)));
System.out.println(current);
}
}
Output:
2019-08-13T00:11:32.409600512Z
Learn about 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.
1 Why is 1899-12-30 the zero date in Access / SQL Server instead of 12/31?
The time format is daysSinceEpoch.fractionOfCurrentDay
The daysSinceEpoch starting at 1899-12-30 instead of 1900-01-01
The fractionOfCurrentDay is a millionth of the current day, ranging from zero to 999999 (23:59:59)
You can use the following function to convert to LocalDateTime:
public static LocalDateTime convert( final String jconsoleDateFormat )
{
String[] split = jconsoleDateFormat.split( "\\." );
long daysSinceEpoch = Long.parseLong( split[0] );
long dayFraction = Long.parseLong( split[1] );
LocalDateTime epochDate = LocalDateTime.of( 1899,12,30, 0,0 );
LocalDateTime currentDate = epochDate.plusDays( daysSinceEpoch );
long secondsADay = 24 * 60 * 60L; // 86_400
long secondsSinceDayStarted = secondsADay * dayFraction / 1_000_000;
return currentDate.plusSeconds( secondsSinceDayStarted );
}
public static void main( String[] args )
{
System.out.println( convert( "43690.008014" ) ); // 2019-08-13T00:11:32
}

Java Generate all dates between x and y [duplicate]

This question already has answers here:
how to get a list of dates between two dates in java
(23 answers)
Closed 6 years ago.
I attempted to generate the date range between date x and date y but failed. I have the same method in c# so I tried to modify it as much as I can but failed to get result. Any idea what I could fix?
private ArrayList<Date> GetDateRange(Date start, Date end) {
if(start.before(end)) {
return null;
}
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
ArrayList<Date> listTemp = new ArrayList<Date>();
Date tmpDate = start;
do {
listTemp.add(tmpDate);
tmpDate = tmpDate.getTime() + MILLIS_IN_DAY;
} while (tmpDate.before(end) || tmpDate.equals(end));
return listTemp;
}
To be honest I was trying to get all the dates starting from january 1st till the end of year 2012 that is december 31st. If any better way available, please let me know.
Thanks
Joda-Time
Calendar and Date APIs in java are really weird... I strongly suggest to consider jodatime, which is the de-facto library to handle dates.
It is really powerful, as you can see from the quickstart: http://joda-time.sourceforge.net/quickstart.html.
This code solves the problem by using Joda-Time:
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
public class DateQuestion {
public static List<DateTime> getDateRange(DateTime start, DateTime end) {
List<DateTime> ret = new ArrayList<DateTime>();
DateTime tmp = start;
while(tmp.isBefore(end) || tmp.equals(end)) {
ret.add(tmp);
tmp = tmp.plusDays(1);
}
return ret;
}
public static void main(String[] args) {
DateTime start = DateTime.parse("2012-1-1");
System.out.println("Start: " + start);
DateTime end = DateTime.parse("2012-12-31");
System.out.println("End: " + end);
List<DateTime> between = getDateRange(start, end);
for (DateTime d : between) {
System.out.println(" " + d);
}
}
}
You could use this function:
public static Date addDay(Date date){
//TODO you may want to check for a null date and handle it.
Calendar cal = Calendar.getInstance();
cal.setTime (date);
cal.add (Calendar.DATE, 1);
return cal.getTime();
}
Found here.
And what is the reason of fail? Why you think that your code is failed?
tl;dr
Year year = Year.of ( 2012 ) ; // Represent an entire year.
year
.atDay( 1 ) // Determine the first day of the year. Returns a `LocalDate` object.
.datesUntil( // Generates a `Stream<LocalDate>`.
year
.plusYears( 1 ) // Returns a new `Year` object, leaving the original unaltered.
.atDay( 1 ) // Returns a `LocalDate`.
) // Returns a `Stream<LocalDate>`.
.forEach( // Like a `for` loop, running through each object in the stream.
System.out :: println // Each `LocalDate` object in stream is passed to a call of `System.out.println`.
)
;
java.time
The other Answers are outmoded as of Java 8.
The old date-time classes bundled with earlier versions of Java have been supplanted with the java.time framework built into Java 8 and later. See Tutorial.
LocalDate (date-only)
If you care only about the date without the time-of-day, use the LocalDate class. The LocalDate class represents a date-only value, without time-of-day and without time zone.
LocalDate start = LocalDate.of( 2016 , 1 , 1 ) ;
LocalDate stop = LocalDate.of( 2016 , 1 , 23 ) ;
To get the current date, specify a time zone. For any given moment, today’s date varies by time zone. For example, a new day dawns earlier in Paris than in Montréal.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
We can use the isEqual, isBefore, and isAfter methods to compare. In date-time work we commonly use the Half-Open approach where the beginning of a span of time is inclusive while the ending is exclusive.
List<LocalDate> localDates = new ArrayList<>();
LocalDate localDate = start;
while ( localDate.isBefore( stop ) ) {
localDates.add( localDate );
// Set up the next loop.
localDate = localDate.plusDays( 1 );
}
LocalDate::datesUntil
You can obtain a stream of LocalDate objects.
Stream< LocalDate > dates = start.datesUntil( stop ) ;
dates.forEach( System.out::println ) ;
LocalDateRange
If doing much of this work, add the ThreeTen-Extra library to your project. This gives you the LocalDateRange class to represent your pair of start and stop LocalDate objects.
Instant (date-time)
If you have old java.util.Date objects, which represent both a date and a time, convert to the Instant class. An Instant is a moment on the timeline in UTC.
Instant startInstant = juDate_Start.toInstant();
Instant stopInstant = juDate_Stop.toInstant();
From those Instant objects, get LocalDate objects by:
Applying the time zone that makes sense for your context to get ZonedDateTime object. This object is the very same moment on the timeline as the Instant but with a specific time zone assigned.
Convert the ZonedDateTime to a LocalDate.
We must apply a time zone as a date only has meaning within the context of a time zone. As we said above, for any given moment the date varies around the world.
Example code.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate start = ZonedDateTime.ofInstant( startInstant , zoneId ).toLocalDate();
LocalDate stop = ZonedDateTime.ofInstant( stopInstant , zoneId ).toLocalDate();
You can use joda-time.
Days.daysBetween(fromDate, toDate);
Found at joda-time homepage.
similar question in stackoverflow with some good answers.
Look at the Calendar API, particularly Calendar.add().

How to compare two Dates without the time portion?

I would like to have a compareTo method that ignores the time portion of a java.util.Date. I guess there are a number of ways to solve this. What's the simplest way?
Update: while Joda Time was a fine recommendation at the time, use the java.time library from Java 8+ instead where possible.
My preference is to use Joda Time which makes this incredibly easy:
DateTime first = ...;
DateTime second = ...;
LocalDate firstDate = first.toLocalDate();
LocalDate secondDate = second.toLocalDate();
return firstDate.compareTo(secondDate);
EDIT: As noted in comments, if you use DateTimeComparator.getDateOnlyInstance() it's even simpler :)
// TODO: consider extracting the comparator to a field.
return DateTimeComparator.getDateOnlyInstance().compare(first, second);
("Use Joda Time" is the basis of almost all SO questions which ask about java.util.Date or java.util.Calendar. It's a thoroughly superior API. If you're doing anything significant with dates/times, you should really use it if you possibly can.)
If you're absolutely forced to use the built in API, you should create an instance of Calendar with the appropriate date and using the appropriate time zone. You could then set each field in each calendar out of hour, minute, second and millisecond to 0, and compare the resulting times. Definitely icky compared with the Joda solution though :)
The time zone part is important: java.util.Date is always based on UTC. In most cases where I've been interested in a date, that's been a date in a specific time zone. That on its own will force you to use Calendar or Joda Time (unless you want to account for the time zone yourself, which I don't recommend.)
Quick reference for android developers
//Add joda library dependency to your build.gradle file
dependencies {
...
implementation 'joda-time:joda-time:2.9.9'
}
Sample code (example)
DateTimeComparator dateTimeComparator = DateTimeComparator.getDateOnlyInstance();
Date myDateOne = ...;
Date myDateTwo = ...;
int retVal = dateTimeComparator.compare(myDateOne, myDateTwo);
if(retVal == 0)
//both dates are equal
else if(retVal < 0)
//myDateOne is before myDateTwo
else if(retVal > 0)
//myDateOne is after myDateTwo
Apache commons-lang is almost ubiquitous. So what about this?
if (DateUtils.isSameDay(date1, date2)) {
// it's same
} else if (date1.before(date2)) {
// it's before
} else {
// it's after
}
If you really want to use the java.util.Date, you would do something like this:
public class TimeIgnoringComparator implements Comparator<Date> {
public int compare(Date d1, Date d2) {
if (d1.getYear() != d2.getYear())
return d1.getYear() - d2.getYear();
if (d1.getMonth() != d2.getMonth())
return d1.getMonth() - d2.getMonth();
return d1.getDate() - d2.getDate();
}
}
or, using a Calendar instead (preferred, since getYear() and such are deprecated)
public class TimeIgnoringComparator implements Comparator<Calendar> {
public int compare(Calendar c1, Calendar c2) {
if (c1.get(Calendar.YEAR) != c2.get(Calendar.YEAR))
return c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
if (c1.get(Calendar.MONTH) != c2.get(Calendar.MONTH))
return c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
return c1.get(Calendar.DAY_OF_MONTH) - c2.get(Calendar.DAY_OF_MONTH);
}
}
My preference would be to use the Joda library insetad of java.util.Date directly, as Joda makes a distinction between date and time (see YearMonthDay and DateTime classes).
However, if you do wish to use java.util.Date I would suggest writing a utility method; e.g.
public static Date setTimeToMidnight(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime( date );
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
Any opinions on this alternative?
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.format(date1).equals(sdf.format(date2));
If you want to compare only the month, day and year of two dates, following code works for me:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.format(date1).equals(sdf.format(date2));
Thanks Rob.
tl;dr
myJavaUtilDate1.toInstant()
.atZone( ZoneId.of( "America/Montreal" ) )
.toLocalDate()
.isEqual (
myJavaUtilDate2.toInstant()
.atZone( ZoneId.of( "America/Montreal" ) )
.toLocalDate()
)
Avoid legacy date-time classes
Avoid the troublesome old legacy date-time classes such as Date & Calendar, now supplanted by the java.time classes.
Using java.time
A java.util.Date represents a moment on the timeline in UTC. The equivalent in java.time is Instant. You may convert using new methods added to the legacy class.
Instant instant1 = myJavaUtilDate1.toInstant();
Instant instant2 = myJavaUtilDate2.toInstant();
You want to compare by date. 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.
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" );
Apply the ZoneId to the Instant to get a ZonedDateTime.
ZonedDateTime zdt1 = instant1.atZone( z );
ZonedDateTime zdt2 = instant2.atZone( z );
The LocalDate class represents a date-only value without time-of-day and without time zone. We can extract a LocalDate from a ZonedDateTime, effectively eliminating the time-of-day portion.
LocalDate localDate1 = zdt1.toLocalDate();
LocalDate localDate2 = zdt2.toLocalDate();
Now compare, using methods such as isEqual, isBefore, and isAfter.
Boolean sameDate = localDate1.isEqual( localDate2 );
See this code run live at IdeOne.com.
instant1: 2017-03-25T04:13:10.971Z | instant2: 2017-03-24T22:13:10.972Z
zdt1: 2017-03-25T00:13:10.971-04:00[America/Montreal] | zdt2: 2017-03-24T18:13:10.972-04:00[America/Montreal]
localDate1: 2017-03-25 | localDate2: 2017-03-24
sameDate: false
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.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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 too prefer Joda Time, but here's an alternative:
long oneDay = 24 * 60 * 60 * 1000
long d1 = first.getTime() / oneDay
long d2 = second.getTime() / oneDay
d1 == d2
EDIT
I put the UTC thingy below in case you need to compare dates for a specific timezone other than UTC. If you do have such a need, though, then I really advise going for Joda.
long oneDay = 24 * 60 * 60 * 1000
long hoursFromUTC = -4 * 60 * 60 * 1000 // EST with Daylight Time Savings
long d1 = (first.getTime() + hoursFromUTC) / oneDay
long d2 = (second.getTime() + hoursFromUTC) / oneDay
d1 == d2
Already mentioned apache commons-utils:
org.apache.commons.lang.time.DateUtils.truncate(date, Calendar.DAY_OF_MONTH)
gives you Date object containing only date, without time, and you can compare it with Date.compareTo
If you're using Java 8, you should use the java.time.* classes to compare dates - it's preferred to the various java.util.* classes
eg; https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
LocalDate date1 = LocalDate.of(2016, 2, 14);
LocalDate date2 = LocalDate.of(2015, 5, 23);
date1.isAfter(date2);
I am afraid there is no method of comparing two dates that could be called "easy" or "simple".
When comparing two time instances with any sort of reduced precision (e.g. just comparing dates), you must always take into account how time zone affects the comparison.
If date1 is specifying an event that occurred in +2 timezone and date2 is specifying an event that occurred in EST, for example, you must take care to properly understand the implications of the comparison.
Is your purpose to figure out if the two events occurred in the same calendar date in their own respective time zones? Or do You need to know if the two dates fall into the same calendar date in a specific time zone (UTC or your local TZ, for example).
Once you figure out what it is actually that You are trying to compare, it is just a matter of getting the year-month-date triple in an appropriate time zone and do the comparison.
Joda time might make the actual comparison operation look much cleaner, but the semantics of the comparison are still something You need to figure out yourself.
Simply Check DAY_OF_YEAR in combination with YEAR property
boolean isSameDay =
firstCal.get(Calendar.YEAR) == secondCal.get(Calendar.YEAR) &&
firstCal.get(Calendar.DAY_OF_YEAR) == secondCal.get(Calendar.DAY_OF_YEAR)
EDIT:
Now we can use the power of Kotlin extension functions
fun Calendar.isSameDay(second: Calendar): Boolean {
return this[Calendar.YEAR] == second[Calendar.YEAR] && this[Calendar.DAY_OF_YEAR] == second[Calendar.DAY_OF_YEAR]
}
fun Calendar.compareDatesOnly(other: Calendar): Int {
return when {
isSameDay(other) -> 0
before(other) -> -1
else -> 1
}
}
If you just want to compare only two dates without time, then following code might help you:
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date dLastUpdateDate = dateFormat.parse(20111116);
Date dCurrentDate = dateFormat.parse(dateFormat.format(new Date()));
if (dCurrentDate.after(dLastUpdateDate))
{
add your logic
}
I don't know it is new think or else, but i show you as i done
SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy");
Date td_date = new Date();
String first_date = dtf.format(td_date); //First seted in String
String second_date = "30/11/2020"; //Second date you can set hear in String
String result = (first_date.equals(second_date)) ? "Yes, Its Equals":"No, It is not Equals";
System.out.println(result);
Here is a solution from this blog: http://brigitzblog.blogspot.com/2011/10/java-compare-dates.html
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Time in days: " + diffDays + " days.");
i.e. you can see if the time difference in milliseconds is less than the length of one day.
`
SimpleDateFormat sdf= new SimpleDateFormat("MM/dd/yyyy")
Date date1=sdf.parse("03/25/2015");
Date currentDate= sdf.parse(sdf.format(new Date()));
return date1.compareTo(currentDate);
`
Using http://mvnrepository.com/artifact/commons-lang/commons-lang
Date date1 = new Date();
Date date2 = new Date();
if (DateUtils.truncatedCompareTo(date1, date2, Calendar.DAY_OF_MONTH) == 0)
// TRUE
else
// FALSE
In Java 8 you can use LocalDate which is very similar to the one from Joda Time.
public Date saveDateWithoutTime(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime( date );
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
This will help you to compare dates without considering the time.
Using the getDateInstance of SimpleDateFormat, we can compare only two date object without time. Execute the below code.
public static void main(String[] args) {
Date date1 = new Date();
Date date2 = new Date();
DateFormat dfg = SimpleDateFormat.getDateInstance(DateFormat.DATE_FIELD);
String dateDtr1 = dfg.format(date1);
String dateDtr2 = dfg.format(date2);
System.out.println(dateDtr1+" : "+dateDtr2);
System.out.println(dateDtr1.equals(dateDtr2));
}
Another Simple compare method based on the answers here and my mentor guidance
public static int compare(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(d1);
c1.set(Calendar.MILLISECOND, 0);
c1.set(Calendar.SECOND, 0);
c1.set(Calendar.MINUTE, 0);
c1.set(Calendar.HOUR_OF_DAY, 0);
c2.setTime(d2);
c2.set(Calendar.MILLISECOND, 0);
c2.set(Calendar.SECOND, 0);
c2.set(Calendar.MINUTE, 0);
c2.set(Calendar.HOUR_OF_DAY, 0);
return c1.getTime().compareTo(c2.getTime());
}
EDIT:
According to #Jonathan Drapeau, the code above fail some cases (I would like to see those cases, please) and he suggested the following as I understand:
public static int compare2(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.clear();
c2.clear();
c1.set(Calendar.YEAR, d1.getYear());
c1.set(Calendar.MONTH, d1.getMonth());
c1.set(Calendar.DAY_OF_MONTH, d1.getDay());
c2.set(Calendar.YEAR, d2.getYear());
c2.set(Calendar.MONTH, d2.getMonth());
c2.set(Calendar.DAY_OF_MONTH, d2.getDay());
return c1.getTime().compareTo(c2.getTime());
}
Please notice that, the Date class is deprecated cause it was not amenable to internationalization. The Calendar class is used instead!
First, be aware that this operation depends on the time zone. So choose whether you want to do it in UTC, in the computer’s time zone, in your own favourite time zone or where. If you are not yet convinced it matters, see my example at the bottom of this answer.
Since your question isn’t quite clear about this, I am assuming that you have a class with an instance field representing a point in time and implementing Comparable, and you want the natural ordering of your objects to be by the date, but not the time, of that field. For example:
public class ArnesClass implements Comparable<ArnesClass> {
private static final ZoneId arnesTimeZone = ZoneId.systemDefault();
private Instant when;
#Override
public int compareTo(ArnesClass o) {
// question is what to put here
}
}
Java 8 java.time classes
I have taken the freedom of changing the type of your instance field from Date to Instant, the corresponding class in Java 8. I promise to return to the treatment of Date below. I have also added a time zone constant. You may set it to ZoneOffset.UTC or ZoneId.of("Europe/Stockholm") or what you find appropriate (setting it to a ZoneOffset works because ZoneOffset is a subclass of ZoneId).
I have chosen to show the solution using the Java 8 classes. You asked for the simplest way, right? :-) Here’s the compareTo method you asked for:
public int compareTo(ArnesClass o) {
LocalDate dateWithoutTime = when.atZone(arnesTimeZone).toLocalDate();
LocalDate otherDateWithoutTime = o.when.atZone(arnesTimeZone).toLocalDate();
return dateWithoutTime.compareTo(otherDateWithoutTime);
}
If you never need the time part of when, it is of course easier to declare when a LocalDate and skip all conversions. Then we don’t have to worry about the time zone anymore either.
Now suppose that for some reason you cannot declare your when field an Instant or you want to keep it an old-fashioned Date. If you can still use Java 8, just convert it to Instant, then do as before:
LocalDate dateWithoutTime = when.toInstant().atZone(arnesTimeZone).toLocalDate();
Similarly for o.when.
No Java 8?
If you cannot use java 8, there are two options:
Solve it using one of the old classes, either Calendar or SimpleDateFormat.
Use the backport of the Java 8 date and time classes to Java 6 and 7, then just do as above. I include a link at the bottom. Do not use JodaTime. JodaTime was probably a good suggestion when the answers recommending it were written; but JodaTime is now in maintenance mode, so the ThreeTen backport is a better and more futureproof option.
The old-fashioned ways
Adamski’s answer shows you how to strip the time part off a Date using the Calendar class. I suggest you use getInstance(TimeZone) to obtain the Calendar instance for the time zone you want. As an alternative you may use the idea from the second half of Jorn’s answer.
Using SimpleDateFormat is really an indirect way of using Calendar since a SimpleDateFormat contains a Calendar object. However, you may find it less troublesome than using Calendar directly:
private static final TimeZone arnesTimeZone = TimeZone.getTimeZone("Europe/Stockholm");
private static final DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
static {
formatter.setTimeZone(arnesTimeZone);
}
private Date when;
#Override
public int compareTo(ArnesClass o) {
return formatter.format(when).compareTo(formatter.format(o.when));
}
This was inspired by Rob’s answer.
Time zone dependency
Why do we have to pick a specific time zone? Say that we want to compare two times that in UTC are March 24 0:00 (midnight) and 12:00 (noon). If you do that in CET (say, Europe/Paris), they are 1 am and 1 pm on March 24, that is, the same date. In New York (Eastern Daylight Time), they are 20:00 on March 23 and 8:00 on March 24, that is, not the same date. So it makes a difference which time zone you pick. If you just rely on the computer’s default, you may be in for surprises when someone tries to run your code on a computer in another place in this globalized world.
Link
Link to ThreeTen Backport, the backport of the Java 8 date and time classes to Java 6 and 7: http://www.threeten.org/threetenbp/.
My proposition:
Calendar cal = Calendar.getInstance();
cal.set(1999,10,01); // nov 1st, 1999
cal.set(Calendar.AM_PM,Calendar.AM);
cal.set(Calendar.HOUR,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
// date column in the Thought table is of type sql date
Thought thought = thoughtDao.getThought(date, language);
Assert.assertEquals(cal.getTime(), thought.getDate());
Using Apache commons you can do:
import org.apache.commons.lang3.time.DateUtils
DateUtils.truncatedEquals(first, second, Calendar.DAY_OF_MONTH)
public static Date getZeroTimeDate(Date fecha) {
Date res = fecha;
Calendar calendar = Calendar.getInstance();
calendar.setTime( fecha );
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
res = calendar.getTime();
return res;
}
Date currentDate = getZeroTimeDate(new Date());// get current date
this is the simplest way to solve this problem.
I solved this by comparing by timestamp:
Calendar last = Calendar.getInstance();
last.setTimeInMillis(firstTimeInMillis);
Calendar current = Calendar.getInstance();
if (last.get(Calendar.DAY_OF_MONTH) != current.get(Calendar.DAY_OF_MONTH)) {
//not the same day
}
I avoid to use Joda Time because on Android uses a huge space. Size matters. ;)
Another solution using Java 8 and Instant, is using the truncatedTo method
Returns a copy of this Instant truncated to the specified unit.
Example:
#Test
public void dateTruncate() throws InterruptedException {
Instant now = Instant.now();
Thread.sleep(1000*5);
Instant later = Instant.now();
assertThat(now, not(equalTo(later)));
assertThat(now.truncatedTo(ChronoUnit.DAYS), equalTo(later.truncatedTo(ChronoUnit.DAYS)));
}
// Create one day 00:00:00 calendar
int oneDayTimeStamp = 1523017440;
Calendar oneDayCal = Calendar.getInstance();
oneDayCal.setTimeInMillis(oneDayTimeStamp * 1000L);
oneDayCal.set(Calendar.HOUR_OF_DAY, 0);
oneDayCal.set(Calendar.MINUTE, 0);
oneDayCal.set(Calendar.SECOND, 0);
oneDayCal.set(Calendar.MILLISECOND, 0);
// Create current day 00:00:00 calendar
Calendar currentCal = Calendar.getInstance();
currentCal.set(Calendar.HOUR_OF_DAY, 0);
currentCal.set(Calendar.MINUTE, 0);
currentCal.set(Calendar.SECOND, 0);
currentCal.set(Calendar.MILLISECOND, 0);
if (oneDayCal.compareTo(currentCal) == 0) {
// Same day (excluding time)
}
If you strictly want to use Date ( java.util.Date ), or without any use of external Library. Use this :
public Boolean compareDateWithoutTime(Date d1, Date d2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
return sdf.format(d1).equals(sdf.format(d2));
}
Date today = new Date();
Date endDate = new Date();//this
endDate.setTime(endDate.getTime() - ((endDate.getHours()*60*60*1000) + (endDate.getMinutes()*60*1000) + (endDate.getSeconds()*1000)));
today.setTime(today.getTime() - ((today.getHours()*60*60*1000) + (today.getMinutes()*60*1000) + (today.getSeconds()*1000)));
System.out.println(endDate.compareTo(today) <= 0);
I am simply setting hours/minutes/second to 0 so no issue with the time as time will be same now for both dates. now you simply use compareTo. This method helped to find "if dueDate is today" where true means Yes.

Categories