Getting date in GMT from unix timestamp [duplicate] - java

This question already has answers here:
How can I get the current date and time in UTC or GMT in Java?
(33 answers)
Closed 9 years ago.
I have written the following code to get the date in GMT from a unix timestamp
private Date converToDate(String unixTimeStamp)
{
//unix timestamps have GMT time zone.
DateFormat gmtFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
//date obtained here is in IST on my system which needs to be converted into GMT.
Date time = new Date(Long.valueOf(unixTimeStamp) * 1000);
String result = gmtFormat.format(time);
return lineToDate(result, true);
}
this code upon execution has
Mon May 27 02:57:32 IST 2013
value in the date variable and
Sun May 26 21:27:32 GMT 2013
in the result variable , How do I directly get the value in result variable into date variable ?

This is the problem, conceptually:
//date obtained here is in IST on my system which needs to be converted into GMT.
Date time = new Date(Long.valueOf(unixTimeStamp) * 1000);
A Date doesn't have a time zone. This is the value you want. The fact that when you call toString() it converts it to your local time zone is irrelevant to the value that it's actually representing. A Date is just a number of milliseconds since the Unix epoch (1st January 1970, midnight UTC). So your whole method can be:
private static Date convertToDate(String unixTimeStamp)
{
return new Date(Long.valueOf(unixTimeStamp) * 1000);
}
You don't need any kind of formatter, as you're not really trying to get a textual representation.
I would advise you to use Joda Time for date/time work if you can, by the way - it's a much cleaner API.

A Date is just the wrapper for a long, which contains a number of milliseconds.
What you're seeing is the default toString() representation of the Date object, which uses your default timezone (IST) to transform the date into a readable string. If you want the date represented as a string using the GMT timezone, just do what you did: use a date format with the GMT time zone.
The Date object represents an instant on the universal timeline, and doesn't have any timezone.

Related

Local timezone date object to UTC timezone date object [duplicate]

This question already has answers here:
Calendar returns date in wrong time zone
(5 answers)
Closed 3 years ago.
I am trying to convert my datetime that is in local timezone into UTC date time.
Date localDate; // this is local date
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ") ;
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = simpleDateFormat.format(localDate);
i am getting proper converted UTC time in dateStr now i want to convert it into Date object with UTC timezone only
but the moment i do that i am again getting the localDate.
//converting string to date object
simpleDateFormat.parse(dateStr)
does anyone know how can i convert local date object to UTC date object
here is the value i am getting while debugging
here dateStr is showing proper date in UTC but utcDate object is showing the local time
Date class is intended to reflect coordinated universal time (UTC) time. It can be formatted into ANY form you want, e.g. you can format it into your local time zone or UTC time zone.
See from javadoc: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a "leap second." The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.

How to get calender date from a date field in Java in a particular time zone? [duplicate]

This question already has answers here:
How to handle calendar TimeZones using Java?
(9 answers)
Closed 7 years ago.
I have a date stored in a date variable(java.util.Date), (say 2015-4-4 15:30:26-0700) in yyyy-mm-dd hh:mm:ss timezone format. Now if I try to get the calendar day (i.e. 04 april 2015) it gets converted to my local timezone and prints the next day(i.e 05 april 2015). How do I get the calendar day in a particular time zone (say +1:30 GMT)?
I am using the getdate()function from java.util.Date to get the calendar day.
I have a date stored in a date variable(java.util.Date), (say 2015-4-4 15:30:26-0700) in yyyy-mm-dd hh:mm:ss timezone format.
No, you have a Date variable. That doesn't have any particular format. Ignore what toString() tells you - that's just formatting it in your local time zone, in a default format. That doesn't mean the format or time zone is part of the state of the Date object - that just represents a point in time.
It sounds like you want:
// Whatever pattern you want - ideally, specify the locale too
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Whatever time zone you want
format.setTimeZone(...);
String text = format.format(date);
Alternatively, if you just want a Calendar value:
TimeZone zone = ...; // Whatever time zone you want
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(date);
// Now use calendar.get(Calendar.YEAR) etc

DateTime to date conversion, not the correct value

I try to convert a string into a datetime:
String dateString = "2015-01-14T00:00:00-04:00";
DateTimeFormatter df = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
DateTime dt = df.parseDateTime(dateString);
If I display dt.toDate()
I get: Tue Jan 13 23:00:00 EST 2015
So there is a time problem.
Without the DateTimeFormatter, I get the same issue.
It's getting the correct value - basically 4am UTC, which is midnight in a UTC offset of -04:00 (as per the original text), or 11pm on the previous day for EST (as per the displayed result).
The problem is that you're using java.util.Date.toString(), which always returns the date in the system time zone. Note that a java.util.Date only represents an instant in time - it has no notion of a time zone itself, so its toString() method just uses the system default.
If you want to retain the time zone information (or in this case, the offset from UTC information - you don't have a full time zone) then stick to DateTime instead of converting to Date. Ideally, avoid java.util.Date/java.util.Calendar entirely. Stick to Joda Time and/or java.time.*.

How do I set a Calendar with TimeZone?

I have a timestamp that I am trying to put into a Date object, however when I use Calendar, I am running into a strange problem. I seem to be able to unable to create a Date object with the values I want:
public static void main(String args[]){
Date today = new Date();
int hour = 4, min=0, sec=0, ms=64;
Calendar cal = GregorianCalendar.getInstance();
cal.clear();
cal.setTimeZone(TimeZone.getTimeZone("EDT"));
cal.setTime(today);
cal.set(Calendar.HOUR_OF_DAY,hour);
cal.set(Calendar.MINUTE,min);
cal.set(Calendar.SECOND,sec);
cal.set(Calendar.MILLISECOND,ms);
System.out.println("Time is: "+cal.getTime());
}
This produces:
Time is: Mon Jan 13 23:00:00 EST 2014
which is not the result I am looking for.
However, if I comment out the 'setTimeZone' method call, I get the following result:
Time is: Tue Jan 14 04:00:00 EST 2014
This is the result that I am looking for but I am concerned that if I am running on a machine that is not running in the same time zone, I will not get consistent behavior.
This is the result that I am looking for but I am concerned that if I am running on a machine that is not running in the same time zone
it is the problem. The internal representation should be ok, but it prints on local timezone: representation differs from real content.
use SimpleDateFormat http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html and set TimeZone to see the date on the Zone desired.
The problem here is that Java does not know of the timezone "EDT" (Eastern Daylight Time). As a result, Calendar seems to be setting the timezone to GMT.
The timezone needed here is "America/New_York" or "EST5EDT". When either of these values are used, the correct result is produced.
The list of valid Time Zones can be obtained by calling TimeZone.getAvailableIDs()
It is unfortunate that no warnings are produced when the requested Time Zone is not found.
If you can do away with java.util.Date, you can use joda time API to conveniently set these values as desired:
For your query, you can set your already created Calendar instance as a constructor parameter to DateTime.
DateTime dt = new DateTime(cal);
System.out.println(dt.toDateTimeISO());
Output:
2014-01-14T04:00:00.064-05:00
Calendar.getTime() returns a java.util.Date object. Date objects do not know anything about timezones. The Date object that Calendar.getTime() returns does not know to what timezone the Calendar that it came from is set.
When you print a Date object (for example, by implicitly calling toString() object, as you are doing) it is formatted in the default time zone of the machine you are running it on.
If you want to print a Date in a specific timezone, use a SimpleDateFormat, and set the desired timezone on the SimpleDateFormat object. For example:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
df.setTimeZone(TimeZone.getTimeZone("EDT"));
// Will display the date that the calendar is set to in the EDT timezone
System.out.println(df.format(cal.getTime()));
Java Date objects represent the number of milliseconds seconds since January 1, 1970, 00:00:00 GMT due to the fact that the other methods are deprecated. The two ways to "view" a Date object directly are "getTime()" and "toString()" (using "dow mon dd hh:mm:ss zzz yyyy"). Therefore, you are formatting the GMT value to your local timezone.
When working with dates, it is best to think of them as GMT values, and then as a "formatting" exercise when viewing the date.
For comparison, here is that same kind of code but using Joda-Time 2.3.
Avoid the java.util.Date & .Calendar classes.
Never use three-letter codes for time zones. They are neither standardized nor unique. Instead use proper time zone names. In this case, use "America/New_York" or "America/Montreal".
// Use time zone names, such as from this slightly outdated list: http://joda-time.sourceforge.net/timezones.html
DateTimeZone timeZone = DateTimeZone.forID( "America/New_York" );
// Input.
int hour = 4, min = 0, sec = 0, ms = 64;
// Start with now, then adjust the time of day.
DateTime now = new DateTime( timeZone );
DateTime dateTime = now.withHourOfDay( hour ).withMinuteOfHour( min ).withSecondOfMinute( sec ).withMillisOfSecond( ms );
// If needed, translate to a java.util.Date for use with other classes.
java.util.Date date = dateTime.toDate();
Dump to console…
System.out.println( "now: " + now );
System.out.println( "dateTime: " + dateTime );
System.out.println( "date: " + date );
When run…
now: 2014-01-20T21:04:51.237-05:00
dateTime: 2014-01-20T04:00:00.064-05:00
date: Mon Jan 20 01:00:00 PST 2014

Why does "12:00" converted to UTC become "11:00"?

I thought 2011-10-23 12:00:00 would remain the same as UTC and that the Converted date would be 2011-10-23 17:00:00.
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt = formatter.parse("2011-10-23 12:00:00");
LocalDateTime ldt = new DateTime(dt).withZone(DateTimeZone.UTC).toLocalDateTime();
LOGGER.warn("Original date: " + ldt.toDateTime().toDate().toString());
DateTime cvtldt = ldt.toDateTime(DateTimeZone.forID("-05:00"));
LOGGER.warn("Converted date: " + cvtldt.toLocalDateTime().toDateTime().toDate().toString());
I don't understand why the output is minus one hour?
Original date: Sun Oct 23 11:00:00 BST 2011
Converted date: Sun Oct 23 11:00:00 BST 2011
You're using Date.toString() which always uses the local time zone. See how your string contains "BST"?
Ideally, stick to just Joda Time for as much of the time as you can:
Parse with the Joda Time formatters
Don't convert back to Date unless you need to
Don't use Date.toString() if you can possibly avoid it; you have no control over its format.
It's not clear what you're really trying to achieve, but you almost certainly don't want to do this many conversions. For example, you're calling toLocalDateTime() followed by toDateTime() again - which means it's using the system default time zone, after you'd carefully specified UTC in the previous conversion...
Your code contains the following conversions (in this order):
String to Date
Date to DateTime
DateTime to DateTime in UTC
DateTime to LocalDateTime (*)
LocalDateTime to DateTime
DateTime to Date
Date to String
(From the results at *) LocalDateTime to DateTime
DateTime to LocalDateTime
LocalDateTime to DateTime
DateTime to Date
Date to String
What do you think the chances of all those conversions being both necessary and correctly specified are? ;)
Original has changed because conversion to the UTC is done with respect to HOST time zone, so it should change.
Converted had changed, in fact it's the problem of accessing method.
You are getting base time and the modifier is stored in other field.
Try going into debugging mode and you will see that after conversion cvtldt
has toString with modifier.
Regards,
Grzesiek

Categories

Resources