Convert GMT to BST Java - java

I have a date format yyyy/mm/dd hh:mm:ss in GMT format. I want to convert the date from GMT format to BST time. What's the simplest way to do this?

With Java 8, the easiest way is probably to:
parse the date into a LocalDateTime
use it to create a ZonedDateTime using GMT time zone
change the time zone to BST
get the LocalDateTime of that new date
Sample example:
String date = "2015/03/09 10:32:00";
LocalDateTime gmt = LocalDateTime.parse(date, DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"));
ZonedDateTime instant = ZonedDateTime.of(gmt, ZoneId.of("GMT"));
LocalDateTime bst = instant.withZoneSameInstant(ZoneId.of("Europe/London")).toLocalDateTime();
System.out.println(bst);
If you change the month to July, for example, you should see an offset of one hour as expected.
(I assumed that BST is British Summer Time - it could also be Bangladesh Standard Time: in general it is better to use the full name of the time zone to avoid ambiguities).

Related

Java different timezone offset in same timezone

I'm using "Asia/Bangkok" zone id.
That offset is from GMT UTC+07:00.
but when I did followings, then it is not +7:00 when set "01/01/1900 7:00:00.000"
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS");
Date date = dateFormat.parse("01/01/1900 7:00:00.000");
System.out.println(date);
System.out.println(date.getTimezoneOffset());
Date date2 = dateFormat.parse("01/01/1900 6:00:00.000");
System.out.println(date2);
System.out.println(date2.getTimezoneOffset());
The result is
Mon Jan 01 07:00:00 ICT 1900
-402
Mon Jan 01 06:00:00 ICT 1900
-420
I wondered if the offset had changed around 7:00 a.m. on January 1, 1900, so I looked it up on Wikipedia.
https://en.wikipedia.org/wiki/Time_in_Thailand
It was UTC+6:42, but from 1880 to 1920.
I have 3 questions.
Why it happen different time offset between "01/01/1900 7:00:00.000" and "01/01/1900 6:00:00.000"
Where can I see time zone history in Java.
How can I ignore different time offset in same Timezone.
-- additional question --
I understand that I should use LocalDateTime.
What is the best way to ignore offset and convert Date to LocalDateTime?
For example, in the following case, the value of convertedDate2 was converted based on an offset of -402.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy H:mm:ss.SSS");
LocalDateTime originalLdate = LocalDateTime.parse("01/01/1900 7:00:00.000", dateFormatter);
LocalDateTime originalLdate2 = LocalDateTime.parse("01/01/1900 6:00:00.000", dateFormatter);
System.out.println(originalLdate);
System.out.println(originalLdate2);
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS");
Date date = dateFormat.parse("01/01/1900 7:00:00.000");
Date date2 = dateFormat.parse("01/01/1900 6:00:00.000");
LocalDateTime convertedDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
LocalDateTime convertedDate2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println(convertedDate);
System.out.println(convertedDate2);
LocalDateTime convertedDate3 = LocalDateTime.parse(dateFormat.format(date), dateFormatter);
LocalDateTime convertedDate4 = LocalDateTime.parse(dateFormat.format(date2), dateFormatter);
System.out.println(convertedDate3);
System.out.println(convertedDate4);
The result is
1900-01-01T07:00
1900-01-01T06:00
1900-01-01T07:00
1900-01-01T05:42:04
1900-01-01T07:00
1900-01-01T06:00
If I convert it once to String and then to LocalDateTime, as in convertedDate3 and convertedDate4,
then I could convert as my expectation, but I wonder this is the most efficient way or not?
Java runtime timezone information for each version is available here
https://www.oracle.com/java/technologies/tzdata-versions.html
Inside the linked file (for a specific version) you can find links to the actual data used
https://www.iana.org/time-zones/repository/releases/tzcode2021a.tar.gz
https://www.iana.org/time-zones/repository/releases/tzdata2021a.tar.gz
https://www.iana.org/time-zones/repository/releases/tzdb-2021a.tar.lz
Inside the tzdata*.tar.gz you can find a file called asia which contains the data for Bangkok as well.
It contains these entries
# Thailand
# Zone NAME STDOFF RULES FORMAT [UNTIL]
Zone Asia/Bangkok 6:42:04 - LMT 1880
6:42:04 - BMT 1920 Apr # Bangkok Mean Time
7:00 - +07
Link Asia/Bangkok Asia/Phnom_Penh # Cambodia
Link Asia/Bangkok Asia/Vientiane # Laos
So the -402 timezone should be used for all dates before 1/4/1920, but it seems the implementation is using the -402 offset only from 1/1/1900 0:00:00.000 UTC (from 1/1/1900 6:42:04.000 in your timezone) and until 1/4/1920 in your timezone and -420 otherwise. I am not sure, if that is intended or a bug.
How can I ignore different time offset in same Timezone.
If you are actually using timezones in your application, then you should not ignore them.
However, if you are making an application that is intended to be used just in your local timezone, then you can use a DateTime class without timezone information, such as java.time.LocalDateTime.
Also worth noting: even if these timezones would be correct, the historical dates might still be inaccurate, due to modern time rules being applied for all time (see below). So in the end it depends on what your use case is.
A date-time without a time-zone in the ISO-8601 calendar system. The ISO-8601 calendar system is the modern civil calendar system used today in most of the world. It is equivalent to the proleptic Gregorian calendar system, in which today's rules for leap years are applied for all time. For most applications written today, the ISO-8601 rules are entirely suitable. However, any application that makes use of historical dates, and requires them to be accurate will find the ISO-8601 approach unsuitable.
java.util.Date and java.text.SimpleDateFormat are very old classes. Although they mostly work, they are difficult to use properly, especially where timezones are concerned.
Date.getTimezoneOffset is deprecated. Do not use deprecated methods.
The proper way to work with timezone rules is using the java.time, java.time.zone, and java.time.format packages:
ZoneId zone = ZoneId.systemDefault();
DateTimeFormatter dateFormatter =
DateTimeFormatter.ofPattern("MM/dd/yyyy H:mm:ss.SSS");
LocalDateTime date =
LocalDateTime.parse("01/01/1900 7:00:00.000", dateFormatter);
System.out.println(date);
System.out.println(zone.getRules().getOffset(date));
LocalDateTime date2 =
LocalDateTime.parse("01/01/1900 6:00:00.000", dateFormatter);
System.out.println(date2);
System.out.println(zone.getRules().getOffset(date2));
The entire history of a timezone is in the ZoneRules:
System.out.println();
zone.getRules().getTransitions().forEach(System.out::println);
System.out.println();
zone.getRules().getTransitionRules().forEach(System.out::println);
You also asked:
What is the best way to ignore offset and convert Date to LocalDateTime?
You can’t. It is not possible to convert a Date to a LocalDateTime without assuming a timezone.
A Date is a wrapper for the number of milliseconds since 1970-01-01 00:00:00 UTC. You cannot generate a LocalDateTime from that without knowing which timezone to apply to that millisecond count. For example, noon Eastern Time in the US is a different number of milliseconds since 1970 than noon Greenwich time.
You may not realize it, but when you use SimpleDateFormat, you are specifying a timezone. Every SimpleDateFormat has a timezone property. Since your code never set that timezone explicitly, your date format used the system’s default timezone.
That is one reason to avoid DateFormat and SimpleDateFormat: the implicit use of the default timezone leads to errors and confusing behavior (though it is predictable behavior). When you use the java.time package and its subpackages, there is no ambiguity, and far less chance of confusion.

Change GMT to EST time in Java 6

I am trying to convert a GMT time zone from other server to EST considering day light saving to display the correct date but not able to do.
The GMT time format is coming in json String as "yyyy-MM-dd 'T' HH:mm:ss 'Z'". To this format we are setting time zone as EST but not getting correct result.
Example - date coming as "2020-06-02T03:53:57Z" , while the correct date in EST when created was "2020-06-01T11:53:57Z".
To convert between two explicit time zones, specify those time zones on the SimpleDateFormat objects used to parse and re-format the date string.
String input = "2020-06-02T03:53:57Z";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = inputFormat.parse(input);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
outputFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(outputFormat.format(date));
Output
2020-06-01 23:53:57 EDT
As you can see, in June, the time zone is EDT, not EST, and it is certainly not Z, aka UTC.

How to convert Date String to joda DateTime?

I have a date string "Wed Nov 20 00:00:00 IST 2019". How do I convert it to joda DateTime with the pattern "yyyyMMdd".
dateObject.setStartDate(new DateTime().plusDays(1).toString("yyyyMMdd"));
The problem with your String pattern is, that JodaTime does not recognize the 'IST' timezone. (See http://joda-time.sourceforge.net/timezones.html for a list of supported time zones.)
If you always want to parse the date in the same time zone, you could use:
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss 'IST' yyyy").withZone(DateTimeZone.forID("Indian/Mahe"));
DateTime parsed = DateTime.parse("Wed Nov 20 00:00:00 IST 2019", dateTimeFormatter);
Note that I have used IST as a string literal in the pattern format, i.e., this will only work if your date strings always includes the "IST" string.
To add fixed time zone information to your parsed date use withZone on the formatter. I picked a random Indian timezone known to JodaTime, "Indian/Mahe" in this case. Look up the one that matches your time zone in the list of supported time zones.

Convert Date String Mon Mar 30 13:51:35 UTC 2015 to Date Object

I am trying to convert a string such as
String dateString = "Mon Mar 30 13:51:35 UTC 2015";
in a Date Object.
I tried this:
DateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZ yyyy", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("Date Object:"+sdf.parse(dateString));
But the output of the date object is
Mon Mar 30 15:51:35 CEST 2015
as you can see:
1) it forwards the string's time ahead to two hours
2) it changes UTC --> CEST
I tried many solutions, but nothing worked. What is the correct way to do this?
EDIT: my objective here is to have a Date object from that original String. That Date Object should have the same parameters as the date string. In this case, the original hours of day (13) is turned to 15, but the desired is for it to stay at 13. I need this because in my program I will need to compare two different date objects.
EDIT: JAVA 8 SOLUTION
Searching the more recent Java 8, I found a better and more elegant solution. Here is the code
String pattern = "EEE MMM dd HH:mm:ss SSS zzz yyyy";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.UK).withZone(ZoneId.of("UTC"));
final ZonedDateTime parsed = ZonedDateTime.parse(dateString, formatter);
Furthermore, to compare it with, for example, the current time:
ZonedDateTime now = ZonedDateTime.now();
int compared = parsed.compareTo(now);
System.out.println("NOW:"+now.toLocalDateTime()+" PARSED:"+parsed.toLocalDateTime()+" COMPARED:"+compared);
You are doing it correctly. The date is being parsed correctly. You are just printing the date into your local computer timezone. When you do toString() to a date, prints the date in your local machine timezone.
Mon Mar 30 15:51:35 CEST 2015 == Mon Mar 30 13:51:35 UTC 2015
CEST is UTC +2
A java.util.Date does not have a time zone, practically speaking. There is a time zone inside but it cannot be set nor gotten. One of many poor design decisions made in these old date-time classes.
The Date::toString method applies your JVM’s current default time zone when generating the output string. Done with good intentions, but not helpful as it creates the illusion your Date object is in that zone when in fact it is not.
java.time
You are using a troublesome old legacy class, now supplanted by the java.time framework built into Java 8 and later.
Convert from a Date to an Instant, a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myJavaUtilDate.toInstant();
Call toString. The java.time classes use standard ISO 8601 formats when parsing/generating strings.
String output = instant.toString();
To create strings, convert from Instant to OffsetDateTime using the constant ZoneOffset.UTC. Then work with the java.time.format classes to generate the string.
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , ZoneOffset.UTC );
Search Stack Overflow for more info and examples. These issues have addressed hundreds of times already.
Instead of UTC, use GMT when getting the timezone.
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Source
You already have the Date object. If you want to print it in format you want, you can use DateFormat to format the Date object as well:
Date date = sdf.parse(dateString);
System.out.println("Date Object:"+sdf.format(date));
// Use the date object ...

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