How to compare dates using Java [duplicate] - java

This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 6 years ago.
I have a date with the format 2012-02-02(yyyy-MM-dd).
For example if todays date is 2012-02-02 i need to add one and a half days to it which would make it 2012-02-03 06:00:00.0.
And if i have a number of dates of the following format 2012-02-03 06:30:00.0(yyyy-MM-dd HH:MM:SS.SSS) , i need to compare if all these dates are less than,greater than or equal to the date to which one and a half days were added above.
The comparison should also take care of the hours while comparing if the dates are less than,greater than or equal or equal to the other date and time.
How do i achieve the same.

Simple arithmetic approach (faster)
Parse the date using SimpleDateFormat that creates a Date object
Use Date.getTime() to return the UTC value in long
Convert 1 and half days to millis (1.5 Days = 129600000 Milliseconds) and add it to previous step
Use >, < and == or after(), before() and equals() if you want to use Date object itself
API approach (slower)
Use Calendar
add(...) method for adding 1 and half day
use before(), after() and equals() methods of Calendar

well so i hope this will give you a clear idea. Calendar Documentation and SimpleDateFormat Documentaion
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String aDateString = "2012-02-02";
Date date = sdf.parse(aDateString);
System.out.println("reference date:"+date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, 36);
System.out.println("added one and half days to reference date: "+cal.getTime());
String newDateString = "2012-02-03 06:30:00.0";
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date newDate = sdf.parse(newDateString);
System.out.println("new date to compare with reference date : "+newDate);
Calendar newCal = Calendar.getInstance();
newCal.setTime(newDate);
if(cal.after(newCal)){
System.out.println("date is greater than reference that.");
}else if(cal.before(newCal)){
System.out.println("date is lesser than reference that.");
}else{
System.out.println("date is equal to reference that.");
}
OUTPUT :
reference date:Thu Feb 02 00:00:00 IST 2012
added one and half days to reference date: Fri Feb 03 12:00:00 IST 2012
new date to compare with reference date : Fri Feb 03 06:30:00 IST 2012
date is greater than reference that.

Use SimpleDateFormat to convert String to Date
Set date to Calendar instance
use calendar.add(Calendar.HOUR, 36)
Also See
Joda Time API

You need to use Joda date time API.
String strDate="2012-02-02";
DateTime dateTime=DateTime.parse(strDate);
DateTime newDateTime=dateTime.plusHours(18);
System.out.println(dateTime);
System.out.println(newDateTime);

Related

Round java.util.Date to end of day [duplicate]

This question already has answers here:
How to create a Java Date object of midnight today and midnight tomorrow?
(20 answers)
Closed 6 years ago.
I want to round a java.util.Date object to the end of the day, e.g. rounding 2016-04-21T10:28:18.109Z to 2016-04-22T00:00:00.000Z.
I saw Java Date rounding, but wasn't able to find something compareable for the end of the day. It also is not the same as how to create a Java Date object of midnight today and midnight tomorrow?, because I don't want to create a new Date (midnight today or tomorrow), but the next midnight based on any given date.
The DateUtils.ceiling serves your purpose. Pass Calendar.DATE for field value.
Given the documentation of DateUtils, I'm not sure I'd trust it with this.
Assuming you're only interested in a UTC day, you can take advantage of the fact that the Unix epoch is on a date boundary:
public static Date roundUpUtcDate(Date date) {
long millisPerDay = TimeUnit.DAYS.toMillis(1);
long inputMillis = date.getTime();
long daysRoundedUp = (inputMillis + (millisPerDay - 1)) / millisPerDay;
return new Date(daysRoundedUp * millisPerDay);
}
I would strongly urge you to move to the java.time API if you possibly can though.
Traditional way
#Test
public void testDateRound() throws ParseException {
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("2016-04-21T10:28:18.109Z");
System.out.println(date);
Calendar cl = Calendar.getInstance();
cl.setTime(date);
cl.set(Calendar.HOUR_OF_DAY, 23);
cl.set(Calendar.MINUTE, 59);
cl.set(Calendar.SECOND, 59);
cl.set(Calendar.MILLISECOND, 999);
System.out.println(cl.getTime());
cl.add(Calendar.MILLISECOND, 1);
System.out.println(cl.getTime());
}
Output
Thu Apr 21 10:28:18 GMT+03:00 2016
Thu Apr 21 23:59:59 GMT+03:00 2016
Fri Apr 22 00:00:00 GMT+03:00 2016

java.sql.Date is taking wrong date [duplicate]

This question already has answers here:
java.util.Date to java.sql.Date conversion gives wrong month
(2 answers)
Closed 8 years ago.
I am using below code,
private static Date date = new Date (2014-1900,11,25);
System.out.println(date);
It is displaying 2014-12-25. I am unable to understand why it is giving me date as 12?
and if i give
private static Date date = new Date (2014-1900,12,25);
it is returning 2015-01-25.
Can anyone help in comprehend this?
Calendar
It accept December month as 11 because month starts from 0 - 11
First you should not use this Constructor, because it is deprecated.
Second: See the documentation of this consturctor:
Parameters:year -
the year minus 1900.month - the month between 0-11.date - the day of
the month between 1-31.See Also:Calendar
month is a null based value, so 0 --> Jan ... 11 --> Dec
from java docs,
Parameters:
year the year minus 1900.
month the month between 0-11.
date the day of the month between 1-31.
Month's range from 0-11, ie Jan - Dec
Avoid using the depriciated Date() constructor for setting dates, It is recommended to use Calendar class
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.MONTH, Calendar.NOVEMBER);
calendar.set(Calendar.DAY_OF_MONTH, 25);
Date date = calendar.getTime();
You can also use the simpleDateFormat for setting/formatting date values:-
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse("25-11-2014");

Date.compareTo(Date) not working

I am writing an app scenario, where need to match between two date if there are same or not and that I am trying to achieve using Date.compareTo(). But it never return 0 as API said for equal date.
I am getting these dates from Caledar.getTime() but it never
I checked with print to both date object and even they are returning same string.
Sat Nov 15 14:17:41 GMT+05:30 2014, Sat Nov 15 14:17:41 GMT+05:30 2014
Any suggestion, how to check date object if they are equal or not.
I think you forgot to check if the dates milliseconds are the same.
This is the source code of the compareTo method.
public int compareTo(Date anotherDate) {
long thisTime = getMillisOf(this);
long anotherTime = getMillisOf(anotherDate);
return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
}
As you can see this method compares two dates using milliseconds as "time step".
Code for old API:
This code checks if two days are the same. (Without hours, minutes, seconds and milliseconds)
Date date1; //Your initial date
Date date2; //Your initial second date
//Remove hours, minutes, seconds and milliseconds by creating new "clean" Date objects
Date compare1 = new Date(date1.getYear(), date1.getMonth(), date1.getDay());
Date compare2 = new Date(date2.getYear(), date2.getMonth(), date2.getDay());
if(compare1.compareTo(compare2) == 0){
}
But I suggest you don't use Date for this task. Because the getYear, getMonth etc. methods are deprecated I suggest you take a look at newer API's like GregorianCalendar and Calendar
Code for new API
This code checks if two days are the same including hours and minutes. But without seconds and milliseconds.
Date date1;
Date date2;
Calendar compareCalendar1 = Calendar.getInstance();
Calendar compareCalendar2 = Calendar.getInstance();
compareCalendar1.setTime(date1);
compareCalendar2.setTime(date2);
//Set for both calendars the seconds and milliseconds to 0
compareCalendar1.set(Calendar.MILLISECOND, 0);
compareCalendar1.set(Calendar.SECOND, 0);
compareCalendar2.set(Calendar.MILLISECOND, 0);
compareCalendar2.set(Calendar.SECOND, 0);
if(compareCalendar1.compareTo(compareCalendar2) == 0){
}
Try to understand compare scenario :
Date date1 = Calendar.getInstance().getTime();
Date date2 = Calendar.getInstance().getTime();
date1.compareTo(date2) >> -1
AND
Date date3 = Calendar.getInstance().getTime();
Date date4 = date3;
date3.compareTo(date4) >> 0

Date Class error in java

I have Date today=new Date(); which returns the current date.. but when i try to display date,month,year separately with the help of
DateFormat mmFormat=new SimpleDateFormat("MM");
System.out.println(mmFormat.format(today.getMonth()));
DateFormat yyFormat=new SimpleDateFormat("yyyy");
System.out.println(yyFormat.format(today.getYear()));
it prints month as 01 and year as 1970
how to resolve this.?
mmFormat.format(today.getMonth())
You're passing an integer – the month of the date – to a date format method.
The format method interprets that integer as a UNIX timestamp – a number of seconds since 1970.
You need to pass the date itself to the formatter.
Pass the entire date to SimpleDateFormat. The format string "MM" or "yyyy" will cause it to just extract the part of the date you want.
Just use the Date today as the input argument
System.out.println(mmFormat.format(today));
and
System.out.println(yyFormat.format(today));
today.getMonth() and today.getYear() returns an int which is interpreted as an UNIX timestamp . The value is 1 and 113 , which corresponds to approximately January 1, 1970, 00:00:01 GMT and January 1, 1970, 00:01:53 GMT represented by this Date object. To get the desired result , you need to pass the Date object :
System.out.println(mmFormat.format(today));
You would need to use Calendar. Have a look at the java docs.
You can do it like this -
Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.MONTH)); // month in the Calendar class begins from 0
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));
System.out.println(cal.get(Calendar.SECOND));
This would help you to avoid creating multiple DateFormat objects. Also in case you want to use another date instead of today's date the you can just pass the date to the cal.setTime() method.
That is because all these methods are deprecated. Use
Calendar myCalendar = GregorianCalendar.getInstance();
myCalendar.get(Calendar.MONTH);
myCalendar.get(Calendar.YEAR);
myCalendar.get(Calendar.DAY_OF_MONTH);
Better in this way
Date date=new Date(); // your date
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(year+"\n"+month);

in java, equivalent to date(String) method?

I want to get the difference between two times. I.e., current time and time1 (like "17 Jun 2011 01:59:25"). By one way, we can do by using Date(string). But it is deprecated method. How to do this with a non-deprecated method?
Use java.text.SimpleDateFormat to parse a string into a Date object. For example:
String text = "17 Jun 2011 01:59:25";
DateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
Date date = df.parse(text);
You can get the time difference between two Date objects by calling getTime() on them and subtracting the values:
Date now = new Date();
long diff = now.getTime() - date.getTime();
System.out.println("Time difference in milliseconds: " + diff);
If you want to know the difference in seconds, minutes, hours, etc. then divide the number of milliseconds by the appropriate factor.
There is comment on deprecated tag
replaced by DateFormat.parse(String s)

Categories

Resources