[英]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.