将ISO8601 T-Z格式的字符串转换为日期

问题描述 投票:16回答:3

可能的解决方案:Convert Java Date into another Time as Date format

我经历了它,但没有得到答案。

我有一个字符串“ 2013-07-17T03:58:00.000Z”,我想将其转换为我们在创建新Date()时获得的相同格式的日期。Dated = new Date ();

时间应该在IST区域-亚洲/加尔各答

因此上述字符串的日期应为

IST 2013年7月17日星期三//根据印度标准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);
java date datetime simpledateformat
3个回答
23
投票

将日历用于时区。

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();

为此,我建议Joda Time,因为它在这种情况下具有更好的功能。对于JodaTime,您可以执行以下操作:

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();

4
投票

日期没有任何时区。如果您想知道日期的字符串表示形式在印度时区中是什么,请使用另一个时区设置为“印度标准”的SimpleDateFormat,并使用此新的SimpleDateFormat格式化日期。

编辑:代码示例:

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));

输出(当前时区是巴黎-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

0
投票

java.time

© www.soinside.com 2019 - 2024. All rights reserved.