Date timezone issue - java

I have a UI where user can enter date. Now this date is converted to UTC format in my code which is inside an EJB.
My Query is if the browser in IST and my code is deployed in an server which in EST.
Now to convert to UTC from which timezone I need to convert the date from IST or ETC.
My code is like:
User enters a date in DatePicker. The value of DatePicker is assigned to plain Java Date Object.

You need to do IST to UTC
Your user is selecting date assuming it is IST. So in your server code you need to consider the user time zone before creating a Date object which will be in server time zone. Since server is in EST you need to convert it again to UTC before storing.
Most of the servers have time configured at UTC time zone, so only one conversion is all that is needed in that case.

When you get a Date its in the local time zone.
private static final DateFormat FULL_RFC822_DATETIME_FORMAT = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss", Locale.US);
public static void date2() throws Exception {
FULL_RFC822_DATETIME_FORMAT.setTimeZone(new SimpleTimeZone(0, "GMT")); //frozen
Date d = new Date(); // in local time zone
System.out.println(d);
System.out.println(FULL_RFC822_DATETIME_FORMAT.format(d) + " GMT");
}
I get
Fri Dec 07 11:15:58 CET 2012
Fri, 7 Dec 2012 10:15:58 GMT
GMT + UTC are the same.

Related

Convert a GMT datetime to local timezone datetime

In Java 8 I need a way to get the local datetime (GMT+1) from a GMT datetime in ISO 8601 format.
A simple example:
Client sends me (Server) this datetime "2020-01-11T23:00:00.000Z"
Client sends me this when the user choose the 12 Jan 2020 from the datepicker. Is the 12 Jan for GMT+1 but the day before for GMT.
For the reason above then I know that for me this datetime is not the 11 Jan 2020 but 12 Jan 2020 in GMT+1.
So I need this value "2020-01-12T00:00:00.000"
To be precise I don't need to print this with simpleDateFormat but just covert "2020-01-11T23:00:00.000Z" to "2020-01-12T00:00:00.000" in a java.util.Date class field
Thanks.
The problem is that the source system took the pure date value, but added time at midnight, then converted that to UTC, but you want the pure date value in a java.util.Date, which by default prints in your local time zone, i.e. the JVM's default time zone.
So, you have to parse the string, revert the value back to the time zone of the source system, the treat that local time as a time in your own JVM's default time zone.
You can do that like this, showing all the intermediate types:
String sourceStr = "2020-01-11T23:00:00.000Z";
ZoneId sourceTimeZone = ZoneOffset.ofHours(1); // Use real zone of source, e.g. ZoneId.of("Europe/Paris");
// Parse Zulu date string as zoned date/time in source time zone
Instant sourceInstant = Instant.parse(sourceStr);
ZonedDateTime sourceZoned = sourceInstant.atZone(sourceTimeZone);
// Convert to util.Date in local time zone
ZonedDateTime localZoned = sourceZoned.withZoneSameLocal(ZoneId.systemDefault());
Instant localInstant = localZoned.toInstant();
Date localDate = Date.from(localInstant); // <== This is your desired result
// Print value in ISO 8601 format
String localStr = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(localDate);
System.out.println(localStr);
Output
2020-01-12T00:00:00.000
The code can of course be merged together:
String input = "2020-01-11T23:00:00.000Z";
Date date = Date.from(Instant.parse(input).atZone(ZoneOffset.ofHours(1))
.withZoneSameLocal(ZoneId.systemDefault()).toInstant());
System.out.println(date);
Output
Sun Jan 12 00:00:00 EST 2020
As you can see, the date value is correct, even though I'm in the US Eastern time zone.

How to parse date with only month and year with SimpleDateFormat

I am working with expiration date of card. I have a API where I will get expiration date in "yyMM" format as "String". Here I am trying to use
SimpleDateFormat with TimeZone.getTimeZone("UTC")
So my code is like
String a= "2011";
SimpleDateFormat formatter = new SimpleDateFormat("yyMM");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = formatter.parse(a);
System.out.println(date);
Now problem is, when I am passing 2011 the out it gives is Sat Oct 31 17:00:00 PDT 2020
Here you can see I am passing 11 as month but it is converting it to Oct instead of Nov.
Why?
And what other options I can use to convert string with yyMM to Date with Timezone?
You should use the Java 8 YearMonth class.
String a = "2011";
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("yyMM");
YearMonth yearMonth = YearMonth.parse(a, inputFormat);
DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("MMMM yyyy");
System.out.println(yearMonth.format(outputFormat));
Output
November 2020
You parsed it fine, but it's printed in PDT, your local timezone.
Sat Oct 31 17:00:00 PDT 2020
Well, Date doesn't track timezones. The Calendar class does, which is internal to the formatter. But still, default print behavior is current timezone.
If you logically convert this output back to UTC, and it will be November 1 since PDT is UTC-7.
Basically, use java.time classes. See additional information here How can I get the current date and time in UTC or GMT in Java?

Converting java.util.Date to java.sql.Timestamp results into wrong value

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

Calendar.getTime() not returning UTC date if TimeZone is defined

I have done this for my Calendar instance to return Date in UTC timezone:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:SS Z");
TimeZone tz = TimeZoneUtil.getTimeZone(StringPool.UTC);
formatter.setTimeZone(tz);
Date dtStart = null;
Date dtEnd = null;
try{
dtStart = formatter.parse(formatter.format(startDate.getTime()));
dtEnd = formatter.parse(formatter.format(endDate.getTime()));
}catch (Exception e) {
e.getStackTrace();
}
It works fine till I format calendar timestamp to return a string date with required timezone but when I parse that string date to Date date, it again picks up local timezone?
I need to store Date object in UTC timezone.
Any help will be highly appreciated!
You can use this:
Date localTime = new Date();
//creating DateFormat for converting time from local timezone to GMT
DateFormat converter = new SimpleDateFormat("dd/MM/yyyy:HH:mm:ss");
//getting GMT timezone, you can get any timezone e.g. UTC
converter.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("local time : " + localTime);;
System.out.println("time in GMT : " + converter.format(localTime));
It will give:
local time: Fri Jun 21 11:55:00 UTC 2013
time in GMT : 21/06/2013:11:55:00
I hope it will help.
Cheers.
Date object in java will always store the values in the host machine (your system) time zone information.
This is from javadoc :
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.
You should trying using Joda Time which is much advanced.
Instead of setting TimeZone in multiple places, it is a good idea to set timezone using -Duser.timezone=GMT or PST.
And, you can easily test how Java deals with timezone and getTime() ignores timezone with an actual example:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); // print with timezone
TimeZone timeZone = TimeZone.getTimeZone(ZoneId.of("GMT"));
TimeZone.setDefault(timeZone); // set system timezone as GMT
sdf.setTimeZone(timeZone); // formatter also has a timezone
Date date = new Date();
System.out.println(date); // system says GMT date
System.out.println(date.getTime()); // only prints time in milliseconds after January 1, 1970 00:00:00 GMT
System.out.println(sdf.format(date));
timeZone = TimeZone.getTimeZone(ZoneId.of("America/Los_Angeles"));
TimeZone.setDefault(timeZone); // set system timezone as GMT
sdf.setTimeZone(timeZone); // formatter also has a timezone
date = new Date();
System.out.println(date);
System.out.println(date.getTime()); // prints the same value as above, "not including timezone offset"
System.out.println(sdf.format(date));
// GMT and PDT times are same as getTime() only returns time in ms since UTC for the day ignoring timezone which is mostly used for formatting
Wed Mar 14 22:43:43 GMT 2018
1521067423108
2018-03-14T22:43:43+0000
Wed Mar 14 15:43:43 PDT 2018
1521067423125 // not includes timezone in getTime()
2018-03-14T15:43:43-0700 // formatting looks fine
The good explanation of why Date object taking Current time zone value ,
please refer this SO answer
EDIT.
here I am gonna add some important part of that answers.
java.util.Date is has no specific time zone, although its value is most commonly thought of in relation to UTC. What makes you think it's in local time?
To be precise: the value within a java.util.Date is the number of milliseconds since the Unix epoch, which occurred at midnight January 1st 1970, UTC. The same epoch could also be described in other time zones, but the traditional description is in terms of UTC. As it's a number of milliseconds since a fixed epoch, the value within java.util.Date is the same around the world at any particular instant, regardless of local time zone.

android convert unix time to utc date

I am a little confused with the unix time stamp conversion to java.util.Date involving the time zones.
I have a unix time stamp that is "1367832568". it is a UTC date (Mon May 06 17:29:28 GMT+00:00 2013). when i do following :
Date d = new Date(1367832568 * 1000);
it gives me Mon May 06 17:29:28 GMT+08:00 2013 which is not correct. it should give me:
Mon May 07 01:29:28 GMT+08:00 2013
because the unix time stamp is actually a UTC date. so this is confusing. what should i do to convert the UTC unix time stamp to correctly convert to a UTC Date object.
I'm not sure exactely how are you formatting your date object, but by setting the timezone to the dateformat object (to GMT) I'm able to get
Mon May 06 09:29:28 GMT 2013 AM
which is the same date you are looking for.
long time = 1367832568 * (long) 1000;
Date date = new Date(time);
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy a");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Log.d("date", format.format(date));

Categories