Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String in ISO8601 T-Z format to Date

Possible Solution:Convert Java Date into another Time as Date format

I went through it but does not get my answer.

I have a string "2013-07-17T03:58:00.000Z" and I want to convert it into date of the same form which we get while making a new Date().Date d=new Date();

The time should be in IST Zone - Asia/Kolkata

Thus the date for the string above should be

Wed Jul 17 12:05:16 IST 2013 //Whatever Time as per Indian Standard GMT+0530

String s="2013-07-17T03:58:00.000Z";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
TimeZone tx=TimeZone.getTimeZone("Asia/Kolkata");
formatter.setTimeZone(tx);
d= (Date)formatter.parse(s);
like image 862
user2511713 Avatar asked Jul 17 '13 06:07

user2511713


People also ask

What is Z in ISO 8601 date format?

It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time. The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Is 8601 date format SAS?

The SAS ISO 8601 formats for UTC with a time zone offset are based on the following time, datetime, and time zone offsets: the zero meridian time or datetime near Greenwich, England. (The offset is always +|–0000 or +|–00:00.)


2 Answers

Use calendar for timezones.

TimeZone tz = TimeZone.getTimeZone("Asia/Calcutta");
Calendar cal = Calendar.getInstance(tz);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
sdf.setCalendar(cal);
cal.setTime(sdf.parse("2013-07-17T03:58:00.000Z"));
Date date = cal.getTime();

For this however I'd recommend Joda Time as it has better functions for this situation. For JodaTime you can do something like this:

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTime dt = dtf.parseDateTime("2013-07-17T03:58:00.000Z");
Date date = dt.toDate();
like image 183
Mark M Avatar answered Nov 16 '22 01:11

Mark M


A Date doesn't have any time zone. If you want to know what the string representation of the date is in the indian time zone, then use another SimpleDateFormat, with its timezone set to Indian Standard, and format the date with this new SimpleDateFormat.

EDIT: code sample:

String s = "2013-07-17T03:58:00.000Z";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date d = formatter.parse(s);

System.out.println("Formatted Date in current time zone = " + formatter.format(d));

TimeZone tx=TimeZone.getTimeZone("Asia/Calcutta");
formatter.setTimeZone(tx);
System.out.println("Formatted date in IST = " + formatter.format(d));

Output (current time zone is Paris - GMT+2):

Formatted Date in current time zone = 2013-07-17T05:58:00.000+02
Formatted date in IST = 2013-07-17T09:28:00.000+05
like image 31
JB Nizet Avatar answered Nov 16 '22 00:11

JB Nizet