簡體   English   中英

將字符串時間戳調整為GMT

[英]Adjust String timestamp to GMT

我有一個當地時間的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但GMT時間?

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

使用dateFormat.format()將Date值恢復為所需的格式。

正如我對這個問題的評論所表明的那樣,我認為這個問題的原始海報對日期時間的工作感到困惑和混淆。 盡管如此,我還是寫了一些示例代碼,提供了皮埃爾所要求的內容,以及我的一些警告,即他正在遵循一些非常糟糕的做法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM