我已尝试使用以下代码将本地日期时间转换为UTC日期时间。但他们也是如此。我想我在这里遗漏了一些东西。任何人都可以帮助我如何从本地日期时间10/15/2013 09:00 AM GMT+05:30
获取UTC日期时间。我从外部系统获得的日期时间字符串,因此如果需要,我可以更改格式。
SimpleDateFormat outputFormatInUTC = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa z");
String startDateTime = "10/15/2013 09:00 AM GMT+05:30";
Date utcDate = outputFormatInUTC.parse(startDateTime);
答案 0 :(得分:0)
只需设置TimeZone
:
SimpleDateFormat outputFormatInUTC = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa z");
String startDateTime = "10/15/2013 09:00 AM GMT+05:30";
outputFormatInUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcDate = outputFormatInUTC.parse(startDateTime);
String timeInUTC = outputFormatInUTC.format(utcDate);
System.out.println(timeInUTC);
输出:
10/15/2013 03:30 AM UTC
答案 1 :(得分:0)
试试这个:
SimpleDateFormat outputFormatInUTC = new SimpleDateFormat("MM/dd/yyyy hh:mm aaa z");
System.out.println(new Date()); //prints local date-time
outputFormatInUTC.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(outputFormatInUTC.format(new Date())); //prints UTC date-time
答案 2 :(得分:0)
是的,如果你可以改变字符串的格式,你应该。为此目的存在一个国际标准:ISO 8601。与此2013-12-26T21:19:39+00:00
或此2013-12-26T21:19Z
一样。
避免使用java.util.Date/Calendar类。他们是出了名的坏人。 Java 8使用新的java.time。* JSR 310类来取代它们。在此期间,您可以使用启发JSR 310的Joda-Time库。
下面的示例代码使用在Mac上运行Java 7的Joda-Time 2.3。
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
String string = "10/15/2013 09:00 AM GMT+05:30";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy hh:mm aaa zZ" );
DateTime dateTime = formatter.parseDateTime( string );
System.out.println( "dateTime: " + dateTime );
跑步时......
dateTime: 2013-10-15T03:30:00.000Z