2012-12-12 46 views
0

我有本地時間String調整字符串時間戳GMT

"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但GMT時間?

+0

你試過'Z'時區?我不認爲'+ SSSS'會做你的想法。 –

+0

@PeterLawrey。謝謝,我會嘗試。 –

+0

你說2012-12-12T08:26:51 + 000是你當地的時間,但抵消格林威治時間是+000。也許你的意思是+0200? –

回答

2

dateFormat.parse()方法返回Date的一個實例,當您調用toString()時,日期將以默認語言環境打印。

使用dateFormat.format()將您的日期值恢復爲您所需的格式。

+0

謝謝。正是我在找的東西。 –

0

正如我對這個問題的看法所表明的那樣,我相信這個問題的原始海報很困惑,並且對日期時間工作有所瞭解。儘管如此,我寫了一些示例代碼,提供了Pierre要求的完整代碼,以及我的警告,說他正在遵循一些非常糟糕的做法。

使用喬達時間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