簡體   English   中英

如何將字符串轉換為特定時區的DateTime,並准確保留該時區的日期?

[英]How can I convert a string into a DateTime for a specific timezone, preserving the date exactly is it comes for that timezone?

我建立了一個函數,該函數接收字符串格式的日期和時區ID,並以時區時間轉換該日期:

public static DateTime transformSrcTimeInTzTime(String timeAsString, String timezoneId){
    DateTimeZone zone = DateTimeZone.forID(timezoneId);
    DateTimeZone.setDefault(zone);
    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
    DateTime tzDate = formatter.parseDateTime(timeAsString);
    System.out.println("++++ timeAsString: " + tzDate.toString(formatter));
    DateTimeZone.setDefault(DateTimeZone.forID(Constants.SERVER_TIMEZONE));
    return tzDate;
}

我不喜歡DateTimeZone.setDefault的部分; 有什么辦法可以做到這一點嗎?

只需設置DateTimeFormatter本身的區域。

DateTimeZone zone = DateTimeZone.forID(timezoneId);
DateTimeFormatter formatter = DateTimeFormat
                      .forPattern("dd/MM/yyyy HH:mm:ss")
                      .withZone(zone);
DateTime tzDate = formatter.parseDateTime(timeAsString).withZone(zone);
return tzDate;

暫無
暫無

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

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