How to convert this unix time string to java date - java

I got this time string "2015-07-16T03:58:24.932031Z", I need to convert to a java timestamp, I use the following code, seems the converted date is wrong?
public static void main(String[] args) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'");
Date date = format.parse("2015-07-16T03:58:24.932031Z");
System.out.println("date: " + date);
System.out.println("timestamp: " + date.getTime());
}
output:
date: Thu Jul 16 04:13:56 CST 2015
timestamp: 1436991236031
Is my date format wrong?
Thanks in advance!

You don't want to quote the Z, it's a timezone indicator. Instead, use the X format specifier, for an ISO-8601 timezone.
Separately, you may want to pre-process the string a bit, because the part at the end, .932031, isn't milliseconds (remember, there are only 1000ms in a second). Looking at that value, it's probably microseconds (millionths of a second). SimpleDateFormat doesn't have a format specifier for microseconds. You could simply use a regular expression or other string manipulation to remove the last three digits of it to turn it into milliseconds instead.
This (which assumes you've done that trimming) works: Live Copy
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
// Note --------------------------------------------------------^^^^
Date date = format.parse("2015-07-16T03:58:24.932Z");
// Note trimming --------------------------------^
System.out.println("date: " + date);
System.out.println("timestamp: " + date.getTime());

Related

Convert time to milliseconds using SimpleDateFormat

I am trying to write a utility function which converts the accepts date,timestamp,milliseconds additional to timestamp and return the time in milliseconds. However, I am getting a parse Exception for that.
Example params:
dateJson: 14.11.2016
timestampJson: 21:04:20
millisecsJson: 244
public static long convertToMillisecs(String dateJson, String timestampJson, String millisecsJson) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy'T'HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String inputString = timestampJson + "." + millisecsJson;
Date date = sdf.parse(dateJson + 'T' + inputString);
return date.getTime();
}
What has to be changed to get the correct parseable date. It is to be noted that I am using a 24 hour clock and I am based in Germany so using UTC in that case is okay ?
14.11.2016 doesn't match dd-MM-yyyy.
And no, Germany is not in the UTC timezone. Use Europe/Berlin.

Java TimeZone Conversion producing opposite results.

Here is the sample I am using.
import java.util.*;
import java.text.*;
public class TimeZoneTest
{
public static final String UTC_ZONE = "UTC";
static String utcDateString = "01/11/2016 11:00:00";
public static void main (String [] args)
{
DateFormat df;
try{
df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println("Original Date : " + utcDateString);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(utcDateString);
System.out.println(" In its Date format : " + date.toString());
System.out.println(" In its GMT format : " + date.toGMTString());
System.out.println(" In its Local format : " + date.toLocaleString());
}
catch (ParseException ex)
{
System.out.println("Exception!!!!");
}
}
}
Here is the output produced.
Original Date : 01/11/2016 11:00:00
In its Date format : Mon Jan 11 06:00:00 EST 2016
In its GMT format : 11 Jan 2016 11:00:00 GMT
In its Local format : Jan 11, 2016 6:00:00 AM
When using the time 11:00:00 and setting the TimeZone to UTC, I was expecting that the 11:00:00 which is my local time (Eastern) representation would then be converted to UTC which would produce 16:00:00.
Instead, it seems to take the string value 11:00:00 and process it as the UTC time instead of local time and return back my local time which is 06:00:00.
Is this the expected results?
When you set the timezone, is it supposed to convert the time being parsed (11:00:00 ) to that timezone and produce (16:00:00)?
OR
When you set the timezone, is it supposed to treat the time being parsed (11:00:00 ) as though it was in that timezone and return the local time (06:00:00)?
You're last statement is true: "OR When you set the timezone, is it supposed to treat the time being parsed (11:00:00 ) as though it was in that timezone and return the local time (06:00:00)?"
Basically, you set the timezone in the DateFormat, then you parse a date without timezone information, so it'll use the timezone from the DateFormat, to convert the String to certain amount of milliseconds from January 1, 1970. Then, you print that date with "toString" that will convert it back to String using your machine's timezone. But the date is the same throughout the program, just different format/timezone.

Parsing time stamp strings from a different time zone

I have a String with timestamp in GMT. I want to convert this to a DateTime object in EST.
E.g If the string has:
final String gmtTime = "20140917-18:55:25"; // 4:55 PM GMT
I need to convert this to : 20140917-12:55:25 //12:55 PM EST
All these tries failed:
System.out.println("Time in GMT " + DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").parseDateTime(gmtTime));
System.out.println("Time in EST " +
DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").parseDateTime(gmtTime).withZone(DateTimeZone.forID("America/New_York")));
Output:
Time in GMT 2014-09-17T18:55:25.000-04:00
Time in EST 2014-09-17T18:55:25.000-04:00 //I expect: 2014-09-17T12:55:25.000-04:00
Any suggestions?
Joda-Time
Here a Joda-Time 2.4 solution:
String gmtTime = "20140917-18:55:25";
DateTime dateTimeGMT =
DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").withZoneUTC().parseDateTime(gmtTime);
System.out.println("Time in GMT " + dateTimeGMT); // Time in GMT 2014-09-17T18:55:25.000Z
System.out.println(
"Time in EST "
+ DateTimeFormat.forPattern("yyyyMMdd-HH:mm:ss").withZone(
DateTimeZone.forID("America/New_York")
).print(dateTimeGMT)
); //Time in EST 20140917-14:55:25
I think that you have the wrong expectation regarding the result. EST (more correct to use is "America/New_York" as zone identifier) is four hours behind UTC, hence the local timestamp there is four hours earlier than the local representation of the same moment at UTC-offset.
Also note that I set the timezone on the formatter not on the parsed DateTime-object.
#Test
public void TimeZoneTest() {
Date now = new Date();
String DATE_PATTERN = "yyyyMMdd-HH:mm:ss";
DateFormat dfEST = new SimpleDateFormat(DATE_PATTERN);
dfEST.setTimeZone(TimeZone.getTimeZone("America/New_York"));
DateFormat dfGMT = new SimpleDateFormat(DATE_PATTERN);
dfGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dfEST.format(now));
System.out.println(dfGMT.format(now));
}
And the output is:
20140919-09:02:19
20140919-13:02:19

To get the date time in the format I give

I have a Java Date object containing date and time information, e.g.2010-11-11T09:30:47. I want to write a method that will convert this Date object to the following format.
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
I wrote the following code.
private Calender getValue(Date dateObject) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
String timestamp = formatter.format(dateObject);
System.out.println("Created GMT cal with date [" + timestamp + "]");
}
When I run the program, it is printing
Created GMT cal with date [2010-11-11T04:00:47.000Z]
What I gave is "2010-11-11T09:30:47", My time is 09:30:47. What it is printing is "04:00:47".
Why the time is changing 9.30 to 4.00.?
What do I need to do to get the same time as I give. Like 2010-11-11T09:30:47.000Z
Thanks a lot.
You just need to remove the following line
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
Because you are setting the Timezone to be GMT, whereas your timezone is GMT + 5.30. That is the reason when you set the time to 9.30, you will get 9.30 - 5.30 = 4.00.
You can just use the following code:
private void getValue(Date dateObject)
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String timestamp = formatter.format(dateObject);
System.out.println("Created GMT cal with date [" + timestamp + "]");
}
Your date probably has the time 09:30:47 in your time zone. But you configured the date format to the GMT time zone. So it's displaying the time as it is in the GMT time zone.
If you used another date format to parse the input string and get a Date object, make sure this oter date format also uses the GMT time zone.
To get more help, show us how you create the Date object passed to your method.
Remove formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String timestamp = formatter.format(new Date());
System.out.println("Created GMT cal with date [" + timestamp + "]");

Local date & time to UTC and then UTC to local date & time

I am trying to convert locale time to UTC, and then UTC to locale time. But I am not getting the result.
public class DateDemo
{
public static void main(String args[])
{
DateFormat dateFormatter =
DateFormat.getDateTimeInstance
(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
TimeZone.setDefault(TimeZone.getDefault());
SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat simpleTimeFormatter = new SimpleDateFormat("hh:mm:ss a");
Date today = new Date();
String localeFormattedInTime = dateFormatter.format(today);
try
{
Date parsedDate = dateFormatter.parse(localeFormattedInTime);
System.out.println("Locale:" + localeFormattedInTime);
System.out.println("After parsing a date: " + parsedDate);
simpleDateFormatter.setTimeZone(TimeZone.getDefault());
simpleTimeFormatter.setTimeZone(TimeZone.getDefault());
String date = simpleDateFormatter.format(today);
String time = simpleTimeFormatter.format(today);
System.out.println("Today's only date: " + date);
System.out.println("Today's only time: " + time);
//// Locale to UTC converting
simpleDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
simpleTimeFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcDate = simpleDateFormatter.format(today);
String utcTime = simpleTimeFormatter.format(today);
System.out.println("Convert into UTC's date: " + utcDate);
System.out.println("Convert into UTC's only time: " + utcTime);
//// UTC to locale converting
simpleDateFormatter.setTimeZone(TimeZone.getDefault());
simpleTimeFormatter.setTimeZone(TimeZone.getDefault());
Date getDate = simpleDateFormatter.parse(utcDate);
Date getTime = simpleTimeFormatter.parse(utcTime);
String getLocalDate = simpleDateFormatter.format(getDate);
String getLocalTime = simpleTimeFormatter.format(getTime);
System.out.println("Get local date: " + getLocalDate);
System.out.println("Get local time: " + getLocalTime);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I am sending local date & time to the web service, and then when require I need to retrieve the UTC date & time and then convert into locale date & time (i.e. user's local settings).
Sample Output:
Locale:11/9/12 8:15 PM
After parsing a date: Fri Nov 09 20:15:00 SGT 2012
Today's only date: 09/11/2012
Today's only time: 08:15:30 PM
Convert into UTC's date: 09/11/2012
Convert into UTC's only time: 12:15:30 PM
Get local date: 09/11/2012
Get local time: 12:15:30 PM
After Saksak & ADTC answers:
For the code fragment, UTC date & time (what is actually coming as GMT-5 because database may be in USA) is the input, and I want to get local date & time as output. But this following segment is still giving GMT-5 time.
SimpleDateFormat simpleDateTimeFormatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
....
Date inDateTime = simpleDateTimeFormatter.parse(intent.getExtras().getString("inTime")); Date outDateTime = simpleDateTimeFormatter.parse(intent.getExtras().getString("outTime"));
simpleDateTimeFormatter.setTimeZone(TimeZone.getDefault()); simpleDateTimeFormatter.setTimeZone(simpleDateTimeFormatter.getTimeZone());
//TimeZone tzTimeZone = TimeZone.getDefault();
//System.out.println("Current time zone: " + tzTimeZone.getDisplayName());
String getLocalInTimeString = simpleDateTimeFormatter.format(inDateTime);
String getLocalOutTimeString = simpleDateTimeFormatter.format(outDateTime);
My question: getLocalInTimeString & getLocalOutTimeString still showing GMT-5 timing. What's wrong here? Do I need to set any other things?
What you need to do to solve your problem is the following, you have your code to convert back to local time in this order :
simpleDateFormatter.setTimeZone(TimeZone.getDefault());
simpleTimeFormatter.setTimeZone(TimeZone.getDefault());
Date getDate = simpleDateFormatter.parse(utcDate);
Date getTime = simpleTimeFormatter.parse(utcTime);
and what you need to do is wait until you parse utcDate, utcTime Strings back to Date Object
then set the date formatter time zone to local zone as follows :
Date getDate = simpleDateFormatter.parse(utcDate);
Date getTime = simpleTimeFormatter.parse(utcTime);
simpleDateFormatter.setTimeZone(TimeZone.getDefault());
simpleTimeFormatter.setTimeZone(TimeZone.getDefault());
this should print the correct date/time in local.
Edit:
here is the full main method :
public static void main(String[] args) {
DateFormat dateFormatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
TimeZone.setDefault(TimeZone.getDefault());
SimpleDateFormat simpleDateFormatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat simpleTimeFormatter = new SimpleDateFormat("hh:mm:ss a");
Date today = new Date();
String localeFormattedInTime = dateFormatter.format(today);
try {
Date parsedDate = dateFormatter.parse(localeFormattedInTime);
System.out.println("Locale:" + localeFormattedInTime);
System.out.println("After parsing a date: " + parsedDate);
simpleDateFormatter.setTimeZone(TimeZone.getDefault());
simpleTimeFormatter.setTimeZone(TimeZone.getDefault());
String date = simpleDateFormatter.format(today);
String time = simpleTimeFormatter.format(today);
System.out.println("Today's only date: " + date);
System.out.println("Today's only time: " + time);
//// Locale to UTC converting
System.out.println("TimeZone.getDefault() >>> " + TimeZone.getDefault());
simpleDateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
simpleTimeFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcDate = simpleDateFormatter.format(today);
String utcTime = simpleTimeFormatter.format(today);
System.out.println("Convert into UTC's date: " + utcDate);
System.out.println("Convert into UTC's only time: " + utcTime);
//// UTC to locale converting
/**
** //////EDIT
*/
// at this point your utcDate,utcTime are strings that are formated in UTC
// so first you need to parse them back to Dates using UTC format not Locale
Date getDate = simpleDateFormatter.parse(utcDate);
Date getTime = simpleTimeFormatter.parse(utcTime);
// NOW after having the Dates you can change the formatters timezone to your
// local to format them into strings
simpleDateFormatter.setTimeZone(TimeZone.getDefault());
simpleTimeFormatter.setTimeZone(TimeZone.getDefault());
String getLocalDate = simpleDateFormatter.format(getDate);
String getLocalTime = simpleTimeFormatter.format(getTime);
System.out.println("Get local date: " + getLocalDate);
System.out.println("Get local time: " + getLocalTime);
} catch (ParseException e) {
e.printStackTrace();
}
}
Your problem is in lines 54 and 55:
Date getDate = simpleDateFormatter.parse(utcDate);
Date getTime = simpleTimeFormatter.parse(utcTime);
These lines are merely parsing Strings that contain the date and time, but these strings do not have any timezone information:
utcDate = "09/11/2012"
utcTime = "12:15:30 PM"
Therefore the parser assumes that the Strings are already in the locale of the timezone you set in lines 51 and 52.
Now think about how to fix it ;) HINT: Make sure the parser is assuming the correct timezone of the time represented by the strings.
PS: [RESOLVED!] I solved the problem but I discovered that the timezone conversion is erratic, for at least where I am. Time is 8:30 pm local. Convert to UTC, 12:30 pm (correct, 8 hr difference). Convert back, it's 8:00 pm (WRONG, eventhough the set timezone is correct - I got the original one and passed it back in - I'm only getting 7.5 hour difference). You should look for more reliable ways unless you can figure out what's going on and how to solve it.
[RESOLUTION:] The problem above was actually because the original code was splitting the date and time into two different parsers. If you use just one parser for both date and time combined you will get the correct date and time in the target locale. So in conclusion the parser is reliable but the way you use it makes a big difference!
SimpleDateFormat simpleDateTimeFormatter
= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Date getDateTime
= simpleDateTimeFormatter.parse(utcDate + " " + utcTime);
//use above line if you have the date and time as separate strings
simpleDateTimeFormatter.setTimeZone(TimeZone.getDefault());
String getLocalDateTime = simpleDateTimeFormatter.format(getDateTime);
System.out.println("Get local date time: " + getLocalDateTime);
WHY USING TWO SEPARATE PARSERS FOR DATE AND TIME IS UNRELIABLE:
As explained above, it's a bad idea to use two separate parsers for date and time parts. Here's why:
Date getDate = simpleDateFormatter.parse(utcDate);
Date getTime = simpleTimeFormatter.parse(utcTime);
//Time zone changed to local here
String getLocalDate2 = simpleDateTimeFormatter.format(getDate);
String getLocalTime2 = simpleDateTimeFormatter.format(getTime);
System.out.println("Get local date2: " + getLocalDate2);
System.out.println("Get local time2: " + getLocalTime2);
OUTPUT:
Get local date2: 10/11/2012 08:00:00 AM
Get local time2: 01/01/1970 10:35:10 AM
I get the half hour difference because the default date 01/01/1970 is used in the Date variable storing time (second line). When this is converted to local timezone, the error happens as the formatter bases its conversion on the default date 01/01/1970 (where I live, the time difference was +7.5 hours in 1970 - today, it is +8 hours). This is why two separate parsers is not reliable even if you get the right result and you must always use a combined parser that accepts both date and time information.

Categories