0

我有一个String当地时间:

"2012-12-12T08:26:51+000"

我现在需要String基于旧的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+SSSSGMT 时间?

4

2 回答 2

2

dateFormat.parse()方法返回一个 Date 的实例,当您调用toString()它时,日期将在默认语言环境中打印。

用于dateFormat.format()将您的日期值恢复为所需的格式。

于 2012-12-12T18:35:24.850 回答
0

正如我对这个问题的评论所暗示的那样,我相信这个问题的原始发帖人对日期时间工作感到困惑和误解。尽管如此,我还是编写了一些示例代码,完全符合 Pierre 的要求,同时我警告说他正在遵循一些非常糟糕的做法。

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

运行时……</p>

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
于 2013-12-10T09:10:01.223 回答