How to Get UTC DateTime - java

How can I get UTC DateTime from the following code? Right now with these lines of code, I get an output like this Fri Dec 31 05:30:00 IST 9999. Is this output is correct? I mean to say is this time is the UTC time. Any suggestions or help?
Code snapshot
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(9999, 11, 31, 0, 0, 0);
Date date = cal.getTime();
System.out.println(date);

Well, the output is correct in that it's what I'd expect for midnight UTC when you're running on a system in IST. Date.toString() always uses your system local time zone - because it doesn't have any other information. A Calendar knows its time zone, but a Date doesn't. The underlying information is just "the number of milliseconds since the Unix epoch".
If you want to convert a Date to a textual representation in a particular time zone, use SimpleDateFormat and specify the time zone there.

The problem here is that you're using the Date.toString() method that returns the local time zone.
You can use this code to get the current time in UTC:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
And then just use that object to get the time you want and use it, do note that cal.getTimeInMillis() or getTime() both return the time from the Epoch that is set to January 1, 1970 00:00:00.000 GMT (Gregorian). So if you want to print the time or use it for something other then calculate the difference in time you can use, for example:
System.out.println(cal.get(Calendar.YEAR));
However if you want to get the difference of time between this time and another you should create another calendar instance for that other time (because of the way getTimeInMillis() work). So you can just do something like:
Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
time.set(Calendar.YEAR, year);
time.set(Calendar.MONTH, month);
time.set(Calendar.DAY_OF_MONTH, day_of_month);
time.set(Calendar.HOUR_OF_DAY, hour_of_day);
time.set(Calendar.MINUTE, minute);
time.set(Calendar.SECOND, second);
long difInMillis = cal.getTimeInMillis() - time.getTimeInMillis();
Also you should always remember that the month starts from 0 and not from 1, to be sure you can use Calendar.[your_month_here] and check the values.
You can find more information here: http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

Related

How Can I Set Miniumum Hour for Date in Java?

I'm trying to get the date and time of the first day of the prior month; specifically as it is January I'm trying to get: Sun Dec 01 00:00:00 EST 2013. I am using the below code snippet which I have modified from another found here on Stackoverflow while researching this subject; this code snippet will return: Sun Dec 01 12:00:00 EST 2013. I do not understand why setting the minimum hour for the 1st in fact returns noon.
Calendar aCalendar = Calendar.getInstance();
// add -1 month to current month
aCalendar.add(Calendar.MONTH, -1);
// set DATE to 1, so first date of previous month
//aCalendar.set(Calendar.DATE, 1);
aCalendar.set(Calendar.DATE, aCalendar.getActualMinimum(Calendar.DAY_OF_MONTH));
aCalendar.set(Calendar.HOUR, aCalendar.getActualMinimum(Calendar.HOUR));
aCalendar.set(Calendar.MINUTE, aCalendar.getActualMinimum(Calendar.MINUTE));
aCalendar.set(Calendar.SECOND, aCalendar.getActualMinimum(Calendar.SECOND));
Date firstDateOfPreviousMonth = aCalendar.getTime();
If I modify the following line as shown and set 0 I get the same result:
aCalendar.set(Calendar.HOUR, 0);
If I modify it as follows I get 1pm:
aCalendar.set(Calendar.HOUR, 0);
Result: Sun Dec 01 13:00:00 EST 2013
From the Java Docs
HOUR Field number for get and set indicating the hour of the morning
or afternoon.
You'll want to use HOUR_OF_DAY instead
HOUR_OF_DAY Field number for get and set indicating the hour of the
day.
Or set the AM_PM accordingly...
AM_PM Field number for get and set indicating whether the HOUR is
before or after noon.
In any case, take the time to consult the Java Docs
Some example code using Joda-Time 2.3.
Using default time zone, we create a DateTime instance of now (current moment), go back to previous month (in a smart manner, compensating for short month like February), get the first of month by asking for "minimum value", and then get first moment of that first-of-month day.
org.joda.time.DateTime startOfPreviousMonth = new org.joda.time.DateTime().minusMonths(1).dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
Note the method withTimeAtStartOfDay to get the first moment of the day. That moment may or may not be 00:00:00 in local time (because of Daylight Saving Time or other anomalies).
Using explicit time zone (almost always a better practice)…
DateTimeZone timeZone = DateTimeZone.forId( "Europe/Paris" ); // "Asia/Kolkata" etc.
org.joda.time.DateTime startOfPreviousMonth = new org.joda.time.DateTime( timeZone ).minusMonths(1).dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
Get a string…
String string = startOfPreviousMonth; // or startOfPreviousMonth.toString();
To convert back to a java.util.Date instance for communicating with other libraries…
java.util.Date date = startOfPreviousMonth.toDate();

Data(timestamp).toLocaleString always return current date

In this code
long timestamp=1332782463298;
Date d=new Date(timestamp);
date=d.toLocaleString();
date is always current date. Where is my mistake?
I've also tried SimpleDateFormat, but it still returns current date:
date=new SimpleDateFormat("MM.dd.yyyy").format(d);
That timestamp is for March 26th 2012 (17:21:03.298 UTC, to be precise). Try a suitably different timestamp (e.g. 1332482563298L) and you'll get a different date...
Note that you shouldn't really be using toLocaleString anyway - SimpleDateFormat is the way to go (or Joda Time if possible). You might also want to consider which time zone you're interested in.
I'm sorry, but do you understand what long timestamp=1332782463298; is ? It's a UNIX time stamp in milliseconds since 1 January 1970, if you keep it same, date will contains same time all the time.
Use Calendar instead:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(1332782463298);
Date d = cal.getTime();
String current = SimpleDateFormat("MM.dd.yyyy").format(cal.getTime()).toString();

Setting TimeZone on instance of Calendar and when calling getTime() the time is not updated based on timezone

I'm trying to take a Date and update it based on another timezome and I've written this code below. I noticed then I set the new time zone which is CST a call to getHour reflects the update but when getTime() the date does not reflect the time based on the timezone last set.
TimeZone zone = TimeZone.getTimeZone(TimeZoneConstants.AmericaNewYork);
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(TimeZoneConstants.AmericaNewYork));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(DateHelper.formatDate(cal.getTime(), DateHelper.FORMAT_TIME_LONG));
Calendar cal2 = Calendar.getInstance();
TimeZone zone2 = cal2.getTimeZone();
cal.setTimeZone(zone2);
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(DateHelper.formatDate(cal.getTime(), DateHelper.FORMAT_TIME_LONG));
output
16
3:14:36 PM CST
15
3:14:36 PM CST
From this the console output is below as you can see the hour is updated but the Date object returned from getTime() is not. I can write a uitl method to get what I want but am wondering why this happens by defauit? - Duncan Krebs
You never changed the time, in terms of raw milliseconds since epoch, at all. Changing the timezone just changes the 'human' representation. 3:14pm Central and 4:14pm Eastern are exactly the same when represented by a java.util.Date. They're both the same amount of raw time since epoch. If you want the human readable representation to be in Eastern time, you need to tell that to the DateHelper doing the formatting.

Facing problem While Converting Date to MilliSeconds

In my Android Application, I am trying to convert Date/Time to Milliseconds, check the below code:
public long Date_to_MilliSeconds(int day, int month, int year, int hour, int minute)
{
Calendar c = Calendar.getInstance();
c.setTimeZone(TimeZone.getTimeZone("UTC"));
c.set(year, month, day, hour, minute, 00);
return c.getTimeInMillis();
}
Problem: I am getting 1290455340800(Nov 22 14:49:00 EST 2010) for Nov 22 19:49:00 EST 2010 (i.e. 5 hours back)
FYI, I am Currently in Indian TimeZone, but application can be executed from any country. so How do i exact Convert the date/time into the Milliseconds?
This line
c.setTimeZone(TimeZone.getTimeZone("UTC"));
Is probably causing the issue. There is no need to set the TimeZone as the current default is used.
My guess is that you're calling Date_to_MilliSeconds(22, 10, 2010, 19, 49). Your code explicitly uses UTC, so it's going to treat whatever you pass it in as UTC.
Just like your previous question (which makes me tempted to close this as a duplicate) it's unclear what you're really trying to do.
If you want to provide a local time to your method, you need to specify a local time zone. If you need to use a local time in the user's time zone, try setting the time zone to TimeZone.getDefault() - although I'd expect that to be the default anyway. If you want to provide a UTC time to your method, you need to specify a UTC time zone (as you are here).
What are you really trying to do?
In this piece of code, you are getting the amount of milliseconds since 01/01/1970 00:00 in your timezone for Nov 22 19:49:00 EST 2010 in UTC timezone. Why are you setting timezone to UTC?
The 5 hours difference is the difference between UTC and EST. You can use DateFormat.parse() to parse the input date if it's a string. Or you can use the code above and pass the desired timezone in c.setTimeZone() -- put in EST instead of UTC.
I'm using this:
public String timeToString(long time, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(time + TimeZone.getDefault().getRawOffset()
+ TimeZone.getDefault().getDSTSavings());
}
I think it solves the TimeZone problems.

Java - Store GMT time

My server has GMT+7, so if i move to another server has another GMT timezone, all date stored in db will incorrect?
Yes Q1 is correct, how about i will store date in GMT+0 timezone and display it in custom GMT timezone chosen by each member
How i get date with GMT+0 in java
1) To quote from the javadocs, Java millisecond timestamps are
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
Therefore, as the timestamp is UTC/GMT, if you store it in the database this date will be correct no matter the time zone of the server.
2) Formatting the timestamp for display depending on the timezone would be the correct approach.
3) Creating a new java.util.Date instance and calling getTime() will get you the timestamp for GMT+0 in Java.
To add to mark's point, once you have a java.util.Date, you can "convert" it to any Timezone (as chosen by the User). Here's a code sample in Groovy (will work in Java with slight mods):
// This is a test to prove that in Java, you can create ONE java.util.Date
// and easily re-display it in different TimeZones
fmtStr = "MM/dd/yyyy hh:mm aa zzz"
myDate = new java.util.Date()
sdf = new java.text.SimpleDateFormat(fmtStr)
// Default TimeZone
println "Date formatted with default TimeZone: " + sdf.format(myDate)
// GMT
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
println "Date formatted with GMT TimeZone: " + sdf.format(myDate)
// America/New_York
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"))
println "Date formatted with America/New_York TimeZone: " + sdf.format(myDate)
// PST
sdf.setTimeZone(TimeZone.getTimeZone("PST"))
println "Date formatted with PST TimeZone: " + sdf.format(myDate)
By default when you get a date in java its in your current timezone, you can use the TimeZone class to get the timezone your system time is running in. Most databases supports that dates can be stored WITH timezone, which probably would be the right way to do this, but exactly what the format is can be dependant on which database you use.
I would suggest that you use Date only as a "holder" and propose that you use Calendar instances instead. To get a Calendar in the GMT time zone just use this:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+00"))
A Calendar will provide a great deal of benefit when you work with times and dates. For instance, adding an hour to this is simple:
cal.add(Calendar.HOUR, 1);
Lastly, when you need a Date you just use this:
Date date = cal.getTime();
For Q3, consider using ZonedDateTime class.

Categories