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
Related
I'm trying to compare two dates using getTime() method but first date is always inferior to the second. After debugging, I figured that the first date (endTime) is taking 31-12-1969 07:00:00 instead of 01-01-1970 07:00:00. This is the code snippet:
if (endTime.before(currentTime)) {
// action
}
Note: I tried it on a different Timezone (UTC) and it worked perfectly the endTime = 01-01-1970 07:00:00. I'm java.util.Date to initialize the endTime.
Any solutions?
Edit:
This method returns the Current Time:
public static Date getCurrentTime() {
Calendar calendar = GregorianCalendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
return new Time(hour, minute, second);
}
This is the initialization of endTime:
Date endTime = new Date();
A timezone can become negative. Try sth. like (pseudocode):
time = time<"01-01-1970 00:00:00" ? "01-01-1970 00:00:00" : time;
But then you compare to UTC instead of timezone. Hope this helps you.
I need to create a custom Date object. I get a user input in 24 hr format like hh:mm i.e. 17:49 hrs.
I want to set the hours and minutes as 17 and 49 respectively keeping other details like month , year , day as per the current time.For e.g if today is Dec 16,2014 and the time is 16:00 hrs , then i want a date object as Dec 16,2014 with time as 17:49 hrs. I know i can do this using deprecated apis , however i do not want to use them.I need the date object because i need to pass it to a java timer as java timer does not support any calendar object.
The user input comes as a string and i can parse that string using new SimpleDateFormat(HH:mm) contructor.
I tried using the Calendar.set apis but had no success.
Could some one give some direction on how to proceed.
PS. Sorry , i can't use Joda time :)
EDIT
Since getHours() and getMinutes() are deprecated and have been replaced with Calendar.HOUR_OF_DAY and Calendar.MINUTE respectively, you could use an intermediary calendar object or set the YEAR and DAY to current values.
There is a problem though, if you input next day hour like 24:01 it won't move to the next day. The previous answer, with splitting of string did the overflowing correctly.
public static void main(String[] args) throws ParseException {
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
final String timeInterval = "12:01";
Date date = simpleDateFormat.parse(timeInterval);
final Calendar calendar = Calendar.getInstance(); //calendar object with current date
calendar.setTime(date); //set date with day january 1 1970, this is because you parsed only the time part, the date objects assumes you start from it's lowest value, try a System.out.println(date) before this to see.
calendar.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
calendar.set(Calendar.DATE,Calendar.getInstance().get(Calendar.DATE));
calendar.set(Calendar.MONTH, Calendar.getInstance().get(Calendar.MONTH))
date = calendar.getTime();
System.out.println(date);
}
You can use Calendar to set the time, then extract the date with .getTime() method, which returns a java.util.Date
The idea is to split your string into two parts based on the separator :.
Then simply initialize the calendar and set the hour and minutes with those values.
public static void main(String[] args) throws ParseException {
final String userInput = "17:49";
final String[] timeParts=userInput.split(":");
Calendar cal=Calendar.getInstance(); //current moment calendar
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(timeParts[0]));
cal.set(Calendar.MINUTE, Integer.parseInt(timeParts[1]));
cal.set(Calendar.SECOND,0); //if you don't care about seconds
final Date myDate=cal.getTime(); //assign the date object you need from calendar
//use myDate object anyway you want ...
System.out.println(myDate);
}
The following code works fine , however i don't want to use any deprecated apis.
...
...
String timeInterval = "18:01";
Date date = simpleDateFormat.parse(timeInterval);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, date.getHours());
calendar.set(Calendar.MINUTE, date.getMinutes());
date = calendar.getTime();
System.out.println(date);
...
...
Probably there will be simply and fast answer but I still cant find out why is the result of
Date date = new Date(60000); //one min.
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(date);
dateStr - 01:01:00
Still one hour more. Time zone? How can I set it without it? Thanks.
Date represents a specific moment in time, not a duration. new Date(60000) does not create "one minute". See the docs for that constructor:
Initializes this Date instance using the specified millisecond value. The value is the number of milliseconds since Jan. 1, 1970 GMT.
If you want "one minute from now" you'll probably want to use the Calendar class instead, specifically the add method.
Update:
DateUtils has some useful methods that you might find useful. If you want the elapsed time in HH:mm:ss format, you might try DateUtils.formatElapsedTime. Something like:
String dateStr = DateUtils.formatElapsedTime(60);
Note that the 60 is in seconds.
Three ways to use java.util.Date to specify one minute:
1. Using SimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")) as shahtapa said:
Date date = new Date(60*1000); //one min.
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
2. Using java.util.Calendar as kabuko said:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.MINUTE,1); //one min.
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
Other calendar.set() statements can also be used:
calendar.set(Calendar.MILLISECOND,60*1000); //one min.
calendar.set(1970,0,1,0,1,0); //one min.
3. Using these setTimeZone and Calendar ideas and forcing Calendar to
UTC Time-Zone
as Simon Nickerson said:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(Calendar.MINUTE,1); //one min.
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
Note: I had a similar issue: Date 1970-01-01 was in my case -3 600 000 milliseconds (1 hour late) java.util.Date(70,0,1).getTime() -> -3600000
I recommend to use TimeUnit
"A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units. A TimeUnit does not maintain time information, but only helps organize and use time representations that may be maintained separately across various contexts. A nanosecond is defined as one thousandth of a microsecond, a microsecond as one thousandth of a millisecond, a millisecond as one thousandth of a second, a minute as sixty seconds, an hour as sixty minutes, and a day as twenty four hours."
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/TimeUnit.html
Date date = new Date(); // getting actual date
date = new Date (d.getTime() + TimeUnit.MINUTES.toMillis(1)); // adding one minute to the date
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);
I'm trying to compare two dates with the current date. It seems not to work when I try to know if a date is the same as the current date. Here's what I do in my code :
//BeginDate is set earlier
Date myDate= new SimpleDateFormat("dd/MM/yyyy").parse(BeginDate);
Date now = new Date();
System.out.println("Now : " + now);
System.out.println("myDate : " + myDate);
System.out.println("equals : " + myDate.equals(now));
System.out.println(myDate.compareTo(now));
And I get this in the console :
Now : Thu Dec 29 00:28:45 CET 2011
myDate : Thu Dec 29 00:00:00 CET 2011
equals : false
-1
The first comparison should return true and the second "0" right ? Or am I missing something ?
Comparing dates with either equals() or compareTo() compares the times (hours, minutes, seconds, millis) as well as the dates. Your test is failing because myDate is midnight today, whereas now is a little later than that.
Your comparison is failing because you need to format now so that both dates have the same format and thus may be compared.
Or, if you prefer, you can convert dates into strings and perform the comparison:
String beginDate = "28/12/2011";
Calendar now = Calendar.getInstance();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String nowStr = df.format(new Date());
System.out.println("equals : " + beginDate.equals(nowStr));
Are you specifying the milliseconds when creating the dates? If you are, don't. So when creating the dates earlier, only specify the Day, Hour etc, not seconds/milliseconds.
And, change the SimpleDateFormat respectively. That "should" work.
Date object in Java is nothing but a number that represents milliseconds since January 1, 1970, 00:00:00 GMT. It doesn't have any attribute called day, date, month, year etc. That's because date, month, year varies based on the type of calendar and timezone. These attributes belong to Calendar instance.
So, if you have 2 Date objects and you want to compare day of month, month and year then you should create corresponding Calendar instance and compare them separately.
// Parse begin date
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date beginDate = dateFormat.parse(beginDateAsString);
// Create calendar instances
Calendar beginDateCalendar = Calendar.getInstance();
beginDateCalendar.setTime(beginDate);
Calendar todayCalendar = Calendar.getInstance();
// Check Equals
boolean dayEquals = todayCalendar.get(Calendar.DAY_OF_MONTH) == beginDateCalendar
.get(Calendar.DAY_OF_MONTH);
boolean monthEquals = todayCalendar.get(Calendar.MONTH) == beginDateCalendar
.get(Calendar.MONTH);
boolean yearEquals = todayCalendar.get(Calendar.YEAR) == beginDateCalendar
.get(Calendar.YEAR);
// Print Equals
System.out.println(dayEquals && monthEquals && yearEquals);
Above code is cumbersome for the current problem but explains how date operations must be done in JAVA.
If you just want to solve the equals problem you have mentioned then the code below will suffice:
String todayAsString = (new SimpleDateFormat("dd/MM/yyyy")).format(new Date());
System.out.println(beginDateAsString.equals(todayAsString));
If you are only going to be dealing with dates between the years 1900 and 2100, there is a simple calculation which will give you the number of days since 1900:
public static int daysSince1900(Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
int year = c.get(Calendar.YEAR) - 1900;
int month = c.get(Calendar.MONTH) + 1;
int days = c.get(Calendar.DAY_OF_MONTH);
if (month < 3) {
month += 12;
year--;
}
int yearDays = (int) (year * 365.25);
int monthDays = (int) ((month + 1) * 30.61);
return (yearDays + monthDays + days - 63);
}
Thus, Date (only) comparison can be achieved by checking if the number of days since 1900 of the 2 dates are equal.
NOTE: The above method should have code added to check if the dates are outside the valid range (1/1/1900 - 31/12/2099) and throw an IllegalArgumentException.
And don't ask me where this calculation came from because we've used it since the early '90s.