This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 9 years ago.
I have two dates:
toDate (user input in MM/dd/yyyy format)
currentDate (obtained by new Date())
I need to compare the currentDate with toDate. I have to display a report only when the toDate is equal to or more than currentDate. How can I do that?
It is easier to compare dates using the java.util.Calendar.
Here is what you might do:
Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-day>);
if(!toDate.before(nowDate)) {
//display your report
} else {
// don't display the report
}
If you're set on using Java Dates rather than, say, JodaTime, use a java.text.DateFormat to convert the string to a Date, then compare the two using .equals:
I almost forgot: You need to zero out the hours, minutes, seconds, and milliseconds on the current date before comparing them. I used a Calendar object below to do it.
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
// Other code here
String toDate;
//toDate = "05/11/2010";
// Value assigned to toDate somewhere in here
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
Calendar currDtCal = Calendar.getInstance();
// Zero out the hour, minute, second, and millisecond
currDtCal.set(Calendar.HOUR_OF_DAY, 0);
currDtCal.set(Calendar.MINUTE, 0);
currDtCal.set(Calendar.SECOND, 0);
currDtCal.set(Calendar.MILLISECOND, 0);
Date currDt = currDtCal.getTime();
Date toDt;
try {
toDt = df.parse(toDate);
} catch (ParseException e) {
toDt = null;
// Print some error message back to the user
}
if (currDt.equals(toDt)) {
// They're the same date
}
Date#equals() and Date#after()
If there is a possibility that the hour and minute fields are != 0, you'd have to set them to 0.
I can't forget to mention that using java.util.Date is considered a bad practice, and most of its methods are deprecated. Use java.util.Calendar or JodaTime, if possible.
You are probably looking for:
!toDate.before(currentDate)
before() and after() test whether the date is strictly before or after. So you have to take the negation of the other one to get non strict behaviour.
This is one of the ways:
String toDate = "05/11/2010";
if (new SimpleDateFormat("MM/dd/yyyy").parse(toDate).getTime() / (1000 * 60 * 60 * 24) >= System.currentTimeMillis() / (1000 * 60 * 60 * 24)) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
A bit more easy interpretable:
String toDateAsString = "05/11/2010";
Date toDate = new SimpleDateFormat("MM/dd/yyyy").parse(toDateAsString);
long toDateAsTimestamp = toDate.getTime();
long currentTimestamp = System.currentTimeMillis();
long getRidOfTime = 1000 * 60 * 60 * 24;
long toDateAsTimestampWithoutTime = toDateAsTimestamp / getRidOfTime;
long currentTimestampWithoutTime = currentTimestamp / getRidOfTime;
if (toDateAsTimestampWithoutTime >= currentTimestampWithoutTime) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
Oh, as a bonus, the JodaTime's variant:
String toDateAsString = "05/11/2010";
DateTime toDate = DateTimeFormat.forPattern("MM/dd/yyyy").parseDateTime(toDateAsString);
DateTime now = new DateTime();
if (!toDate.toLocalDate().isBefore(now.toLocalDate())) {
System.out.println("Display report.");
} else {
System.out.println("Don't display report.");
}
Date long getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
//test if date1 is before date2
if(date1.getTime() < date2.getTime()) {
....
}
private boolean checkDateLimit() {
long CurrentDateInMilisecond = System.currentTimeMillis(); // Date 1
long Date1InMilisecond = Date1.getTimeInMillis(); //Date2
if (CurrentDateInMilisecond <= Date1InMilisecond) {
return true;
} else {
return false;
}
}
// Convert both date into milisecond value .
If for some reason you're intent on using Date objects for your solution, you'll need to do something like this:
// Convert user input into year, month, and day integers
Date toDate = new Date(year - 1900, month - 1, day + 1);
Date currentDate = new Date();
boolean runThatReport = toDate.after(currentDate);
Shifting the toDate ahead to midnight of the next day will take care of the bug I've whined about in the comments to other answers. But, note that this approach uses a deprecated constructor; any approach relying on Date will use one deprecated method or another, and depending on how you do it may lead to race conditions as well (if you base toDate off of new Date() and then fiddle around with the year, month, and day, for instance). Use Calendar, as described elsewhere.
Use java.util.Calendar if you have extensive date related processing.
Date has before(), after() methods. you could use them as well.
Related
This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 7 years ago.
i'm trying the get the Difference between 2 dates time..
i have an arraylist, each object contains data of type Date..
My Questions are:
1) is using Calendar.getInstance().get(Calendar.MINUTE) ... etc the best way to get the current date & Time
2) should i fill manually the data in variable of Date, as follows:
Date currentDate = new Date();
currentDate.setMinutes(Calendar.getInstance().get(Calendar.MINUTE));
currentDate.setHours(Calendar.getInstance().get(Calendar.HOUR));
currentDate.setDate(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
currentDate.setMonth(Calendar.getInstance().get(Calendar.MONTH));
currentDate.setYear(Calendar.getInstance().get(Calendar.YEAR));
3) How to get the Difference between the currentDate and the an old date i have
is it like currentDate - oldDate and what about the "AM_PM" issue, should i do this function manually?
1) is using Calendar.getInstance().get(Calendar.MINUTE) ... etc the best way to get the current date
JavaDoc from java.util.Date empty constructor:
Allocates a Date object and initializes it so that it represents the
time at which it was allocated, measured to the nearest millisecond.
3) How to get the Difference between the currentDate and the an old date i have is it like currentDate - oldDate and what about the "AM_PM" issue, should i do this function manually?
Date oldDate = ...
Date currentDate = new Date();
long dt = currentDate.getTime() - oldDate.getTime();
1) To get the current date:
Date = new Date();
2) TO set manually a Date it is better to work with a Calendar.
Calendar c = new GregorianCalendar();
c.set(Calendar.MONTH, 1);
c.set(Calendar.YEAR, 2015);
// ... and so on
Date date = c.getTime();
3) to calculate the distance in ms between two dates.
Date d1 = ....;
Date d2 = ....;
long distance = d1.getTime() - d2.getTime();
Try this, variable now below is current date.
String givenDate = "03/11/2015";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
try {
Date date = (Date)dateFormat.parseObject(givenDate);
Date now = new Date();
System.out.println(date);
System.out.println(now);
int diffInDays = (int)( (now.getTime() - date.getTime())
/ (1000 * 60 * 60 * 24) );
System.out.println(diffInDays);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can choose any format and add time or AM/PM, see more details of SimpleDateFormat. If you dont have string dates then you can directly use date variable shown above.
Cheers !!
Is there a way to compare two calendar objects, but ignore milliseconds?
I have written a test case that compared two calendar objects, but there is a problem. Although all of the day, month, minutes and hours match, the milliseconds doesn't matches. I get the expected date before getting the real date:
/**
* #return
*/
private Calendar getExpectedOneMonthDateFromCurrentDate() {
Calendar expectedOneMonth = Calendar.getInstance();
expectedOneMonth.add(Calendar.MONTH, -1);
return expectedOneMonth;
}
assertEquals(getExpectedOneMonthDateFromCurrentDate(),
DateRange.LAST_ONE_MONTH.getToDate());
Remove milliseconds from your calendar
cal.set(Calendar.MILLISECOND, 0);
You need to use
cal.set(Calendar.MILLISECOND, 0);
and possibly as well
cal.set(Calendar.SECOND, 0);
if you just need the minutes to match.
The solution of setting the milliseconds to 0 has an issue: if the dates are 12:14:29.999 and 12:14:30.003, you will set the dates to 12:14:29 and 12:14:30 respectively and will detect a difference where you don't want to.
I have thought about a Comparator:
private static class SecondsComparator implements Comparator<Calendar>
{
public int compare(Calendar o1, Calendar o2)
{
final long difference = o1.getTimeInMillis() - o2.getTimeInMillis();
if (difference > -1000 && difference < 1000)
return 0;
else
return difference < 0 ? 1 : -1;
}
}
public static void main(String args[])
{
Calendar c1 = Calendar.getInstance();
Utils.waitMilliseconds(100);
Calendar c2 = Calendar.getInstance();
// will return 0
System.out.println(new SecondsComparator().compare(c1,c2));
}
However, it no a good solution neither, as this Comparator breaks the following rule:
The implementer must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
What leads to (x=y and y=z) => x=z.
So I don't see any solution... But indeed, if you define some different dates, they are different, aren't they?
IMHO the easiest way is to use truncate() from Apache Commons DateUtils (Apache Commons DateUtils) to remove the milliseconds and compare the resulting dates.
If you are on Java 8, you can use the Java Time API, specifically Calendar::toInstant(), followed by Instant::truncatedTo(). Specify the granularity of truncation using ChronoUnit enum.
myCalendar.toInstant().truncatedTo( ChronoUnit.SECONDS ) // Lop off any fractional second.
Example.
Calendar oneMonthIsh = Calendar.getInstance();
oneMonthIsh.add(Calendar.MONTH, -1);
oneMonthIsh.add(Calendar.MINUTE, 1);
assertNotEquals(oneMonthIsh.toInstant(), getExpectedOneMonthDateFromCurrentDate());
assertEquals(oneMonthIsh.toInstant().truncatedTo(ChronoUnit.DAYS),getExpectedOneMonthDateFromCurrentDate().toInstant()
.truncatedTo(ChronoUnit.DAYS));
One option is to call Calendar.set(Calendar.MILLISECOND, 0) to clear the milliseconds. Another is call getTimeInMillis() to get the time in milliseconds for both calendars. You could then divide these by 1000 before comparing to remove the milliseconds.
I'd recommend using Joda Time if you are performing anything beside the basic date manipulations. In your case you can truncate the dates like so and then compare :
DateTime dateTime = new DateTime().millisOfDay().roundFloorCopy();
clearMilis(date1).compareTo(clearMilis(date2))
/**
* #param date date
*
* #return truncated miliseconds
*/
#Nonnull
public static Date clearMillis(final #Nonnull Date date)
{
DateTime result = new DateTime(date);
return result.minusMillis(result.getMillisOfSecond()).toDate();
}
public static String getFromatDateTime(Date date) {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime( date );
//gc.set( Calendar.HOUR_OF_DAY, 0 );
//gc.set( Calendar.MINUTE, 0 );
//gc.set( Calendar.SECOND, 0 );
//block ignore millisecond
gc.set( Calendar.MILLISECOND, 0 );
String strDate = sdfDate.format(gc.getTime());
return strDate;
}
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date now = new Date();
String currentDate = Testing.getFromatDateTime(now);
String fullDate = "2015-12-07 14:53:39.30";
String effDateStr = Testing.getFromatDateTime(sdfDate.parse(fullDate));
System.out.println("Currennt Date: " + currentDate);
System.out.println("Effective Date: " + effDateStr);
System.out.println(currentDate.compareTo(effDateStr)==0);
}
If you use jodaTime, the setCopy("0") method returns a DateTime object with milliseconds set to 0 to make it easy to compare:
DateTime dateTimeZerodMillis = new DateTime().millisOfSecond ().setCopy("0")
Though I am way too late for the party, sharing my simple alternate approach for posterity
Two date objects comparision by ignoring the milliseconds using org.apache.commons.lang3.time.DateUtils
Date date1 = new Date(1503055069000L);
Date date2 = new Date(1503055069683L);
//Here the two dates are differed by 683 milliseconds, if we want to skip just the
//683 milliseconds difference then we can use the below logic
if(DateUtils.setMilliseconds(date1, 0).equals(DateUtils.setMilliseconds(date2, 0))){
//your business process
}
NOTE: DateUtils#setMilliseconds method sets the milliseconds field to a date returning a new object. The original Date is unchanged. so until you are reassigning the object reference the original date object values are unchanged.
On my Android App, I'd like to only re-import my data if it's been at least X hours since the last import.
I'm storing the last_updated time in my sqlite database in this format: 2012/07/18 00:01:40
How can I get "hours from then" or something like that?
My code thus far:
package com.sltrib.utilities;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DateHelper
{
public static String now()
{
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
//System.out.println("Now the date is :=> " + dateNow);
return dateNow;
}
public static int hoursAgo(String datetime)
{
//return the number of hours it's been since the given time
//int hours = ??
//return hours;
}
}
You're going to want to do math between two Calendars or Dates.
Note: Aspects of Date are deprecated, see below for Calendar!
Here's an example using Date:
public static int hoursAgo(String datetime) {
Date date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.ENGLISH).parse(datetime); // Parse into Date object
Date now = Calendar.getInstance().getTime(); // Get time now
long differenceInMillis = now.getTime() - date.getTime();
long differenceInHours = (differenceInMillis) / 1000L / 60L / 60L; // Divide by millis/sec, secs/min, mins/hr
return (int)differenceInHours;
}
There are some try/catch blocks involved here (which you should probably handle with throws), but this is the basic idea.
Edit: Since parts of Date are deprecated, here is the same method using Calendar:
public static int hoursAgo(String datetime) {
Calendar date = Calendar.getInstance();
date.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.ENGLISH).parse(datetime)); // Parse into Date object
Calendar now = Calendar.getInstance(); // Get time now
long differenceInMillis = now.getTimeInMillis() - date.getTimeInMillis();
long differenceInHours = (differenceInMillis) / 1000L / 60L / 60L; // Divide by millis/sec, secs/min, mins/hr
return (int)differenceInHours;
}
You can also do it directly on the query. Look this question, there is examples of how to calculate difference between two dates:
SQLite: express the difference as days, hours, minutes between two given dates
This question already has answers here:
Time: How to get the next friday?
(9 answers)
Closed 6 years ago.
How can I find out the date of last (previous) "Friday" or any other day from a specified date?
public getDateOnDay(Date date, String dayName) {
// ?
}
I won't give an answer (try it yourself first!), but, maybe these tips can help you out.
You first need to figure out the current day of the week you are on. You may want to take a look at Java's Calendar class to get an idea of how to do that.
Once you get the date you are on, think about the modulus operator and how you can use that to move backwards to pick up the previous day that you are looking for from the day you are currently at. (Remember, a week is 7 days and each day of the week takes up a "slot" in those 7 days.)
Once you have the number of days in between, you'll want to subtract. Of course, there are classes that can add and subtract days for you in the Java framework...
I hope that helps. Again, I encourage you to always try the problem for yourself, first. You learn far much more that way and be a better developer in the long run for it.
Here is a brute force idea. Check if current date is friday. If not, subtract 1 day from today. Check if new date is friday. If not, subtract 1 day from new date..... so on.. you get the idea.
Try this one:
/**
* Return last day of week before specified date.
* #param date - reference date.
* #param day - DoW field from Calendar class.
* #return
*/
public static Date getDateOnDay(Date date, int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.WEEK_OF_YEAR, -1);
cal.set(Calendar.DAY_OF_WEEK, day);
return cal.getTime();
}
Good luck.
I'm using this:
private Date getDateOnDay(Date date, int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.setFirstDayOfWeek(day);
cal.set(Calendar.DAY_OF_WEEK, day);
return cal.getTime();
}
Get the day of week for the date. Look at Calendar javadoc. Once you have the day of the week you can calculate an offset to apply to the date.
To get any latest date based on weekday:
private String getWeekDayDate(String weekday){
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar start = Calendar.getInstance();
Date now = new Date();
start.setTime(now);
Calendar end = Calendar.getInstance();
end.add(Calendar.DATE, -7);
while (start.after(end))
{
try {
Date temp = start.getTime();
String day = new SimpleDateFormat("EEEE").format(temp);
if(day.equalsIgnoreCase(weekday))
return formatter.format(temp);
}catch(Exception e) {
e.printStackTrace();
}
start.add(Calendar.DAY_OF_YEAR, -1);
}
return null;
}
To get latest Friday date, give weekday as "Friday"
//gets the last four Fridays from today's date if you want pass in a any date
//just need to tweak the code, the other method just basically formats the date in dd/MM/YYYY format.
function GetLastFourFridays() {
today = new Date();
LastFridayDate = new Date();
LastFridayDate.setDate(LastFridayDate.getDate() - 1);
while (LastFridayDate.getDay() != 5) {
LastFridayDate.setDate(LastFridayDate.getDate() - 1);
}
var lfd = LastFridayDate
lfd = convertDate(lfd)
document.getElementById("first_week_th").innerHTML = lfd
LastFridayDate.setDate(LastFridayDate.getDate() - 1);
var friLastWeek = LastFridayDate
while (friLastWeek.getDay() != 5) {
friLastWeek.setDate(friLastWeek.getDate() - 1);
}
var flw = friLastWeek
flw = convertDate(flw)
document.getElementById("second_week_th").innerHTML = flw
friLastWeek.setDate(friLastWeek.getDate() - 1);
var friTwoWeeks = friLastWeek
while (friTwoWeeks.getDay() != 5) {
friTwoWeeks.setDate(friTwoWeeks.getDate() - 1);
}
var ftw = friTwoWeeks
ftw = convertDate(ftw)
document.getElementById("third_week_th").innerHTML = ftw
friTwoWeeks.setDate(friTwoWeeks.getDate() - 1);
var friThreeWeeks = friTwoWeeks
while (friThreeWeeks.getDay() != 5) {
friThreeWeeks.setDate(friThreeWeeks.getDate() - 1);
}
var ftww = friThreeWeeks
ftww = convertDate(ftww)
document.getElementById("fourth_week_th").innerHTML = ftww
}
//convets the date 00//00//0000
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');}