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

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.

Related

Transformation date to single time zone [duplicate]

This question already has answers here:
Convert timestamp in milliseconds to string formatted time in Java
(10 answers)
Closed 4 years ago.
I have two timestamps as milliseconds, which were created in different time zones and cannot convert to the same time zone.
Date_1 = 1525694035615 - Mon May 07 2018 11:53:55
Date_2 = 1525686835730 - Mon May 07 2018 09:53:55
Does any body know how to identify time zone and get values in UTC+0?
When I transform these timestamps always get values that these timestamps have timezone +0.
If your milliseconds timestamps created in Java they are always milliseconds from
midnight, January 1, 1970 UTC
And have nothing about time zone.
what you see:
Mon May 07 2018 11:53:55
Mon May 07 2018 09:53:55
Just string representations of those moments in time in the current JVM/Computer Time Zone
If you need to have a String representation in UTC time zone there are number of classes to do that. In all JDK there are Calendar implementations (e.g. GregorianCalendar). From Java 8 there is new API inspired by Joda time.
It should work better with timezones handling.
If you are getting timezone+0 that is because that is the default timezone given any fixed time in any amount (milliseconds in your example). You must tell it what timezone you are in if you want a different one that UTC+0.
Does any body know how to … get values in UTC+0?
I’m taking the easy part first:
OffsetDateTime dateTime = Instant.ofEpochMilli(1_525_694_035_615L)
.atOffset(ZoneOffset.UTC);
System.out.println(dateTime);
This prints:
2018-05-07T11:53:55.615Z
This agrees with what you said in the question. The Z in the end means UTC.
…how to identify time zone…
We can’t exactly. If you know the time to which the timestamp corresponds in the timezone where it was produced, we can calculate the offset. Since this is rather boring when the answer is UTC, I am taking a different example:
long timestamp = 1_525_708_128_067L;
LocalDateTime dateTimeInUnknownTimezone = LocalDateTime.of(2018, Month.MAY, 7, 18, 48, 48);
LocalDateTime utcDateTime = Instant.ofEpochMilli(timestamp)
.atOffset(ZoneOffset.UTC)
.toLocalDateTime()
.truncatedTo(ChronoUnit.SECONDS);
int offsetInSeconds = (int) ChronoUnit.SECONDS.between(utcDateTime, dateTimeInUnknownTimezone);
ZoneOffset offset = ZoneOffset.ofTotalSeconds(offsetInSeconds);
System.out.println(offset);
+03:00
Since the date-time has precision of seconds only, I am also truncating the UTC time to seconds to get the offset precise. From the offset of +03:00 we cannot unambiguously determine a time zone, though, since many time zones use this offset.

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.*.

Getting date in GMT from unix timestamp [duplicate]

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.

Is java.util.Date represents date as system date or not? [duplicate]

This question already has answers here:
Closed 10 years ago.
I need to get real world date and time in Java. I use:
Date date = new Date();
But I'm not sure that it is not just system time. I don't need to be dependent on PC local date and time.
If it is so, then is there any way to abstract from it? I mean I need correct time and date. If today is the 1st of May, 2012 and user changed (maybe there was a system error) it to the 1st of December 2000, it shouldn't affect business logic. So is there any alternative to achieve this?
Date only represents an instant in time, in milliseconds since the Unix epoch of January 1st 1970 UTC (modulo leap seconds). It has no concept of a time zone in its data. However, if you use the toString method it will always convert that UTC instant to a local date/time using the system time zone. That confuses a lot of users, making them think that Date contains a time zone - it's just an illusion.
Likewise Date doesn't have any concept of a calendar system (Gregorian, Julian etc) or a "format". Basically it's just a long :)

How to convert a data from 1 timezone to another timezone? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Timezone conversion
I have a date in UTC, how to convert it to other timezone?
java.util.Date
Despite what the output of Date.toString() suggests, Date instances are not timezone aware. They simply represent a point in time, irrespective to the timezone. So if you have a Date instance, there is nothing more you need to do. And what if you have time in one time zone and you want to know what is the time in other time zone? You need
java.util.Calendar
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("Asia/Tokyo"))
cal.set(Calendar.HOUR_OF_DAY, 15) //15:00 in Tokyo
cal.set(Calendar.MONTH, Calendar.NOVEMBER)
cal.setTimeZone(TimeZone.getTimeZone("Australia/Melbourne"))
cal.get(Calendar.HOUR_OF_DAY) //17:00 in Melbourne
Note that after changing the time zone the date (point in time) didn't changed. Only the representation (current hour in this particular time zone). Also note that November is important there. If we change the month to July suddenly the hour in Melbourne changes to 16:00. That's because Tokyo does not observe DST, while Melbourne does.
java.text.DateFormat
There is another catch in Java with time zones. When you are trying to format a date you need to specify time zone explicitly:
DateFormat format = DateFormat.getTimeInstance
format.setTimeZone(TimeZone.getTimeZone("Europe/Moscow"))
Otherwise DateFormat always uses current computer's time zone which is often inappropriate:
format.format(cal.getTime())
Since format() method does not allow Calendar instances (even though it accepts Object as a parameter - sic!) you have to call Calendar.getTime() - which returns Date. And as being said previously - Date instances are not aware of time zones, hence the Tokyo and Melbourne settings are lost.
You can try Joda-Time library. They have 2 functions called withZone() and withZoneRetainFields() to perform timezone calculations.

Categories

Resources