Compare java.util.Calendar date to java.util.Date - java

I need to compare a Calendar time to Date. I wrote below code.
Calendar now = Calendar.getInstance();
now.set(Calendar.SECOND, 0);
Date date = new Date();
date.setSeconds(0);
System.out.println(date);
System.out.println(now.getTime());
System.out.println(date.compareTo(now.getTime()));
Output is
Fri Dec 01 16:54:00 IST 2017
Fri Dec 01 16:54:00 IST 2017
1
It seems util date is bigger than calendar date. Why is it failing? what is the write way of comparing these dates?
Edit 1:-
My problem is I need to compare a util date (stored in database) lets say 2017-12-01 16:41:00.0 to current Date and time, what is write approach?

Check the millis:
System.out.println(now.getTime().getTime());
System.out.println(date.getTime());
System.out.println(now.getTime().getTime() - date.getTime());
Then you see that there (sometimes) is a difference.

A simple way to remove the seconds/millis is to count the number of minutes
// compare the minutes, ignoring the seconds/milli-seconds.
if (now.getTime().getTime() / 60_000 == date.getTime() / 60_000)
You can also use TimeUnit
if (TimeUnit.MILLISECONDS.toMinutes(now.getTime().getTime()) ==
TimeUnit.MILLISECONDS.toMinutes(date.getTime()))
if you prefer to use a library than maths.

Related

Converting java.util.Date to java.sql.Timestamp results into wrong value

Server side code (server timezone is UTC):-
Date aDate = new Date();
java.sql.Timestamp aTimestamp = new java.sql.Timestamp(aDate.getTime());
Client side (Mobile app, timezone GMT +5:30):-
Hitting a service request which runs above code on server side
The issue is when i debugged on server, found following values :-
aDate.getTime() prints to -> 1470472883877 milliseconds i.e., Sat Aug 06 2016 14:11:23 GMT+0530
but
aTimestamp prints to -> (java.sql.Timestamp) 2016-08-06 08:41:44.109
It's kinda weird, i've no idea what's going on in conversion !! please help
UTC and GMT are formats.
java.util.Date and java.sql.Timestamp are independent of the timezone. They store a long time in ms for representing their inner state.
For information, Calendar is timezone aware.
So with Date or Timestamp, to differentiate GMT or UTC format in an output, you have to use a formater which outputs the date into string by being aware the timezone.
In your output : 2016-08-06 08:41:44.109, you don't use a formater which is aware of the timezone. It's probably the result of a toString() on the java.sql.Timestamp instance or something of similar.
What you consider as a conversion is not a conversion but a formatting since the timestamp stays the same between the two objects.
If you want to display in the UTC format, use the appropriate formater with a
SimpleDateFormat for example :
SimpleDateFormat dt= new SimpleDateFormat("MM/dd/yyyy hh:mm:ss z");
dt.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStringInUTC = dt.format(new Date(yourSqlTimestamp.getTime()));
The following is probably what you are looking for:
Calendar cal = Calendar.getInstance(Locale.GERMANY); // use your locale here
Timestamp aTimestamp = new Timestamp(cal.getTimeInMillis());
System.out.println(aTimestamp);
System.out.println(cal.getTime());
And the output:
2016-08-06 19:12:54.613
Sat Aug 06 19:12:54 CEST 2016

Formatting a date in java

I have the two Date objects which I am trying to format from being in MM/DD/YYYY format to "yyyy-mm-dd HH:mm:ss" format.
The current approach I am using is to first format those dates using SimpleDateFormat which will return two Strings, then I have to convert this string back to Date to get the formatted final Date objects.
So I was wondering if there was a simpler way to change the Date object format without going in many steps?
Thanks
The format is irrelevant. Date simply represents the number of milliseconds since the Unix epoch.
Remember, Date has no concept of format, it doesn't care.
You should simply format the Date object with whatever formatters you need...
For example...
Date date = new Date();
System.out.println(date);
System.out.println(DateFormat.getDateTimeInstance().format(date));
System.out.println(new SimpleDateFormat("dd/MM/yyyy").format(date));
System.out.println(new SimpleDateFormat("yyyy MMMM EE").format(date));
System.out.println(new SimpleDateFormat("EEEE MMMM yyyy").format(date));
System.out.println(date);
Outputs...
Wed Jan 22 11:55:18 EST 2014
22/01/2014 11:55:18 AM
22/01/2014
2014 January Wed
Wednesday January 2014
Wed Jan 22 11:55:18 EST 2014
Note how the first and last values don't change. Date has no internal concept of format, that's the responsibility of the formatter.
For example, if I took the String value 22/01/2014 and parsed it back to a Date using SimpleDateFormat
Date date = new SimpleDateFormat("dd/MM/yyyy").parse("22/01/2014");
And then outputted the date value...
System.out.println(date);
It would output something like...
Wed Jan 22 00:00:00 EST 2014
The format has being lost. It would need to use an appropriate formatter to change what is displayed

how to check different date formats in java

I am getting different date formats below dd-MM-yyyy,dd/MM/yyyy,yyyy-MM-dd,yyyy/MM/dd
SimpleDateFormat sm1 = new SimpleDateFormat("dd-MM-yyyy");
String date = "01-12-2013";
System.out.println("Date 1 is "+sm1.parse(date));
date = "2013-12-01";
System.out.println("Date 1 is "+sm1.parse(date));
the same simple date format gives the below result eventhough date format is wrong(ie:-2013-12-01).Below the results.
Date 1 is Sun Dec 01 00:00:00 IST 2013
Date 1 is Sun Jun 05 00:00:00 IST 7
You need to setLenient(false) to make parse() method throw ParseException for unparsable case
I have tried Jigar Joshi's answer.
==========================code=======================================
SimpleDateFormat sm1 = new SimpleDateFormat("dd-MM-yyyy");
sm1.setLenient(false);
String date = "01-12-2013";
System.out.println("Date 1 is "+sm1.parse(date));
date = "2013-12-01";
System.out.println("Date 1 is "+sm1.parse(date));
=========================Result========================================
Date 1 is Sun Dec 01 00:00:00 CST 2013
Exception in thread "main" java.text.ParseException: Unparseable date: "2013-12-01"
at java.text.DateFormat.parse(DateFormat.java:337)
at workflow.Test.main(Test.java:14)
Your date format is dd-MM-yyyy. That means the parser is expecting some day, month, and year format.
From the SimpleDateFormat documentation: the number of pattern letters in a Number type formatter is the minimum. So, while 2013 wouldn't make sense in our mind, it fits within the formatter's bounds.
You have provided 2013-12-01 as to fit into that format. What it appears the formatter is doing is providing December 1 (insert timezone here), and then adding 2,013 days to it.
That turns out to be June 6, 7 AD. There's some wiggle room for your timezone (I'm not sure which of the five timezones IST represents is actually yours).
So, believe it or not...the formatter is correct. Be very careful as to what kind of format you specify or allow in your dates!
If you don't want that parsed, then specify setLenient(false) on your instance of sm1.

Why is my date not being set correctly to 30 days in the future?

I have the following:
Date now = new Date();
Date futureDate = new Date(now.getYear(), now.getMonth(), now.getDay() + 30);
I want to set the future date value to be 30 days in the future, based on the current date (now).
When I debug this, now is the correct date, and the futureDate is:
Sat Jan 05 00:00:00 EST 2013
Today's date, the value of now is: Sat Dec 29 17:31:58 EST 2012.
This doesn't make sense to me?
I'm using util.Date.
Because getDay() returns day of the week, not day of the month.
So your
now.getDay() + 30
becomes Saturday + 30 = 6 + 30 = 36th December = 5th January
A quick fix would be to replace your code with:
now.getDate() + 30
But as others already suggest, java.util.Date is kind of deprecated. And you should use Calendar.add(). So your code would become something like:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, +30);
You should use Calendar and its method Calendar.add
If you want to use Date, you'll see working with adding days is all kinds of deprecated:
http://docs.oracle.com/javase/7/docs/api/java/util/Date.html
Use new Date(now.getTime() + (MILLISECONDS_IN_DAY * 30)) instead. Or if you're not stuck with Date, use Calendar.
Not only is that constructor deprecated, it only accepts valid days (1-31).
try using java.util.Calendar instead.
Date is not supposed to be used for such calculations.
Have a look at JodaTime which is exelent for such things.

Converting unix timestamp to date in Android emulator

I have a timestamp I want to convert to a date. I tried this timestamp: 1336425840. This should be Mon, 07 May 2012 21:24:00 GMT, where GMT is the timezone the emulator should be set to. I tried this:
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(1336425840*1000);
Date d = c.getTime();
Log.i("MyTag", "Hours: " + d.getHours());
The result is: Hours: 23.
So it seems like the returned date is computed according to GMT+2, which is the timezone set for my system. I expected g.hetHours() to return 21, since the emulator's timezone seems to be set to GMT.
Also, that timestamp results from reading the actual date in C using mktime, which seems to return the correct timestamp. But Java seems to refer to a different timezone. Am I doing anything wrong? Why isn't Mon, 07 May 2012 21:24:00 GMT returned?
I'm pretty sure 1336425840*1000 will give you a value outside the regular range of int. In fact, if you would print the full date of the Calendar object, you'll see it displays Thu Jan 08 23:56:50 GMT 1970, which explains the 23 hours you see.
Change the multiplication to: (note the L at the end)
c.setTimeInMillis(1336425840 * 1000L);
// Edit: easy to confirm:
System.out.println((1336425840 * 1000L > Integer.MAX_VALUE));
:)
You should use a DateFormat object, and then set the time zone with setTimeZone().

Categories