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

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

Related

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?

SimpleDateFormat.parse() converts DTstring to local time. Can be converted to source's time?

I have followed this SO answer for datetime conversion of 8601.
I will cite an example straight from w3 :
1994-11-05T08:15:30-05:00 corresponds to November 5, 1994, 8:15:30 am, US Eastern Standard Time.
1994-11-05T13:15:30Z corresponds to the same instant.
And this is what I run in android
SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
dateTime = sdfSource.parse("2014-03-06T11:30:00-05:00");
System.out.println(dateTime); //Thu Mar 06 18:30:00 EET 2014
Obviously .parse()'s output is the local aware datetime. There has been a conversion from EST(-05:00) to EET (+02:00) since now I am in this timezone. However I do not want this auto-convertion.
Is there a way to parse a datetime string inyyyy-MM-dd'T'HH:mm:ssZZZZZ format and display THAT timezone's datetime? Preferable output:
Thu Mar 06 11:30:00 EST 2014
The EST and my location is an example. It can be any other timezones as well.
Internally Date objects are in UTC and that's what they're parsed to.
You cannot retrieve the original timezone from the Date but you can attempt to retrieve it from the original ISO-8601 stamp, and use it when formatting.
When you convert it to a string with toString(), it uses your local settings to format the date. If you want a specific representation, use a formatter to format the output, e.g.
int rawTimeZoneOffsetMillis = ...; // retrieve from ISO-8601 stamp and convert to milliseconds
TimeZone tz = new SimpleTimeZone(rawTimeZoneOffsetMillis, "name");
DateFormat outputFormat = DateFormat.getDateTimeInstance();
outputFormat.setTimeZone(tz);
System.out.println(df.format(dateTime));
ISO-8601 timestamps are not completely parseable with SimpleDateFormat. This answer has some code to work around some of the limitations.
Use sdfSource.setTimeZone() method
SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
sdfSource.setTimeZone(TimeZone.getTimeZone("EST")); //give the timezone you want
dateTime = sdfSource.parse("2014-03-06T11:30:00-05:00");
System.out.println(dateTime); //Thu Mar 06 18:30:00 EET 2014
This should do fine.
Although you should not be worried while parsing the date as it is parsed to correct value can be displayed in any format or timezone you want.
SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
sdfSource.setTimeZone( TimeZone.getTimeZone( "EST" ) );
dateTime = sdfSource.parse("2014-03-06T11:30:00-05:00");
System.out.println(sdfSource.format(dateTime)); //Thu Mar 06 18:30:00 EET 2014

Formatting a date in java

I have the two Date objects which I am trying to format from being in MM/DD/YYYY format to "yyyy-mm-dd HH:mm:ss" format.
The current approach I am using is to first format those dates using SimpleDateFormat which will return two Strings, then I have to convert this string back to Date to get the formatted final Date objects.
So I was wondering if there was a simpler way to change the Date object format without going in many steps?
Thanks
The format is irrelevant. Date simply represents the number of milliseconds since the Unix epoch.
Remember, Date has no concept of format, it doesn't care.
You should simply format the Date object with whatever formatters you need...
For example...
Date date = new Date();
System.out.println(date);
System.out.println(DateFormat.getDateTimeInstance().format(date));
System.out.println(new SimpleDateFormat("dd/MM/yyyy").format(date));
System.out.println(new SimpleDateFormat("yyyy MMMM EE").format(date));
System.out.println(new SimpleDateFormat("EEEE MMMM yyyy").format(date));
System.out.println(date);
Outputs...
Wed Jan 22 11:55:18 EST 2014
22/01/2014 11:55:18 AM
22/01/2014
2014 January Wed
Wednesday January 2014
Wed Jan 22 11:55:18 EST 2014
Note how the first and last values don't change. Date has no internal concept of format, that's the responsibility of the formatter.
For example, if I took the String value 22/01/2014 and parsed it back to a Date using SimpleDateFormat
Date date = new SimpleDateFormat("dd/MM/yyyy").parse("22/01/2014");
And then outputted the date value...
System.out.println(date);
It would output something like...
Wed Jan 22 00:00:00 EST 2014
The format has being lost. It would need to use an appropriate formatter to change what is displayed

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.

Date timezone issue

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.

Categories