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().
Related
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.
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
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.
The below code when run with JDK5(1.5.0_09) prints
Fri May 03 00:00:00 GMT 3912
5/3/12 5:30 AM
and when run with JDK6(1.6.0_23) prints
Fri May 03 00:00:00 IST 3912
5/3/12 12:00 AM
Obviously the difference is because of the timezone used then the Date object is created. But doesn't this cause problems for existing code when the JDK is upgraded? Is this behavior documented somewhere or am I missing something?
class TimeTest {
public static void main(String[] args) {
Date d = new Date(2012, 04, 3);
Locale l = new Locale("en", "US","");
DateFormat df= DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, l );
TimeZone t = TimeZone.getTimeZone("Asia/Calcutta");
df.setTimeZone(t);
System.out.println(d);
System.out.println(df.format(d));
}
}
The strange year 3192 is arising because that deprecated Date constructor assumes you are using a 2-digit year with 0 meaning 1900. It adds 1900 to the year number.
The difference in the timezones is not the fault of the Date constructor. Your code is using TimeZone.getTimeZone("Asia/Calcutta") to get the timezone. That method is documented as returning the GMT timezone if it doesn't recognize the timezone string. It would appear that Sun ADDED support for more timezones in Java 1.6. (Most people would view this as a good thing rather than as a portability concern.)
I haven't tried it, but the following should be sufficient to insulate yourself against using GMT when your requested zone id is unrecognised.
public TimeZone getZone(String id) {
TimeZone tz = TimeZone.getTimeZone();
if (!tz.getID().equals(id)) {
throw new IllegalArgumentException("unrecognized zone " + id);
}
return tz;
}
In summary, your code is broken in two respects:
It is using a deprecated constructor.
It is assuming that getTimeZone will understand all of your timezone Strings, and this is clearly not the case for Java 1.5.
I have problem with getting server date (linux server). When I use linux 'date' command I get properly date value (real date). If I modify some file
on server, modify date is also properly (real date). But if i use java code System.out.println(new Date()) on server I get date with 1 hour difference
i.e. linux 'date' command result = Wed Sep 16 08:48:25 CEST, System.out.println(new Date()) result = Wed Sep 16 07:48:25 GMT+1
Is this linux configuration problem or wrong getting date using java.
Thanks
date --rfc-2822; date +%s
Wed, 16 Sep 2009 09:59:36 +0200
1253087976
System.out.println(new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z").format(new Date()));
System.out.println(new Date().getTime() / 1000);
16 wrz 2009 09:00:33 +0100
1253088033
You must make sure you use the correct time zone before using Date (or Calendar, for that matter - wasn't Date deprecated?).
For instance:
/* Skipping the boring class def part. */
public static void main(String[] args) {
Date date = new Date();
DateFormat myDateFormat = new SimpleDateFormat();
TimeZone firstTime = TimeZone.getTimeZone(args[0]);
myDateFormat.setTimeZone(firstTime);
System.out.println("-->"+args[0]+": " + myDateFormat.format(date));
}
the argument then can be your desired time zone, for example "IST", "GMT", or whatever.
This is probably a timezone/daylight savings issue. Use:
java.util.Timezone.getDefault()
to see which timezone is Java configured to use and whether daylight savings apply or not.
I suggest you upgrade your Java installation. Your JRE likely doesn't have the latest daylight savings rules in place. Java gets the time since the epoch, and uses your current TZ setting to compute what the local time is. DST rules change from time to time, and both the operating system and the JDK need to be updated when this occurs.
Can you add the output of the following to your question:
# unix
date --rfc-2822; date +%s
# Java
System.out.println(new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z").format(new Date()));
System.out.println(new Date().getTime() / 1000);
The should both output something like:
Wed, 16 Sep 2009 17:26:08 +1000
1253085968