我有String
当地时间:
"2012-12-12T08:26:51+000"
我现在需要根据旧String
创建一个GMT时间String
。例如,假设本地和GTM之间有2小时的差异:
"2012-12-12T10:26:51+000"
我创建了一个SimpleDateFormat
:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss+SSSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String time = dateFormat.parse(mCreatedTime).toString();
但是time
字符串现在采用不同的格式:
Wed Dec 12 etc
如何使输出格式为yyy-MM-dd'T'HH:mm:ss+SSSS
但格林威治标准时间?
答案 0 :(得分:2)
dateFormat.parse()
方法返回Date的实例,当您在其上调用toString()
时,日期将以默认语言环境打印。
使用dateFormat.format()
将日期值恢复为所需格式。
答案 1 :(得分:0)
正如我对这个问题的评论所表明的那样,我认为这个问题的原始海报对日期时间的工作感到困惑和混淆。尽管如此,我还是写了一些示例代码,这些代码完全按照皮埃尔的要求提供,同时我还要注意他正在遵循一些非常糟糕的做法。
使用Joda-Time 2.3库和Java 7。
// © 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.*;
// CAUTION: The question asked specifically for the format used here.
// But this format incorrectly uses the PLUS SIGN to mean milliseconds rather than offset from UTC/GMT.
// Very bad thing to do. Will create no end of confusion.
// Another bad thing: This code creates strings representing date-times in different time zones without indicating they are in different time zones.
// Time Zone list: http://joda-time.sourceforge.net/timezones.html
// "Atlantic/South_Georgia" is a time zone two hours behind UTC.
DateTimeZone southGeorgiaZone = DateTimeZone.forID( "Atlantic/South_Georgia" );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss+SSS" );
DateTime dateTimeInSouthGeorgia = formatter.withZone( southGeorgiaZone ).parseDateTime( "2012-12-12T08:26:51+000" );
DateTime dateTimeInUtc = dateTimeInSouthGeorgia.toDateTime( DateTimeZone.UTC );
String screwyBadPracticeDateTimeString = formatter.print( dateTimeInUtc );
System.out.println( "2012-12-12T08:26:51+000 in southGeorgiaDateTime: " + dateTimeInSouthGeorgia );
System.out.println( "same, in UTC: " + dateTimeInUtc );
System.out.println( "screwyBadPracticeDateTimeString: " + screwyBadPracticeDateTimeString );
跑步时......
2012-12-12T08:26:51+000 in southGeorgiaDateTime: 2012-12-12T08:26:51.000-02:00
same, in UTC: 2012-12-12T10:26:51.000Z
screwyBadPracticeDateTimeString: 2012-12-12T10:26:51+000