-3
我一直在尋找這個答案,但我可能是錯誤至於如何實現這一點。我有一個ZonedDateTime變量,目前,如果我要打印出來,將打印,例如2017-12-03T10:15:30 + 01:00。有什麼方法可以打印已經添加或減去偏移量的時間?例如我想看看16:30以上的例子。感謝您的幫助!ZonedDateTime格式顯示當前的時間偏移已經包含
我一直在尋找這個答案,但我可能是錯誤至於如何實現這一點。我有一個ZonedDateTime變量,目前,如果我要打印出來,將打印,例如2017-12-03T10:15:30 + 01:00。有什麼方法可以打印已經添加或減去偏移量的時間?例如我想看看16:30以上的例子。感謝您的幫助!ZonedDateTime格式顯示當前的時間偏移已經包含
看看這個:
public Date parseDateTime(String input) throws java.text.ParseException {
//NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks
//things a bit. Before we go on we have to repair this.
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
//this is zero time so we need to add that TZ indicator for
if (input.endsWith("Z")) {
input = input.substring(0, input.length() - 1) + "GMT-00:00";
} else {
int inset = 6;
String s0 = input.substring(0, input.length() - inset);
String s1 = input.substring(input.length() - inset, input.length());
input = s0 + "GMT" + s1;
}
return df.parse(input);
}
有一點變化,使,使其適合您的需要。你應該可以很輕鬆地做到這一點。然後,你必須Date對象之後,添加你想要的偏移:
int myNumHours = 4; //Any number of hours you want
myDateObject.add(Calendar.HOUR,myNumHours);
//Adds myNumHours to the Hour slot and processes all carrys if needed be.
我們打印:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String myDateString = df.format(myDateObject);
//Now just use your myDateString wherever you want.
如果我理解正確的話,你要做到這相當於在顯示ZonedDateTime實例什麼世界標準時間。你可以在你的DateTimeFormatter上設置時區,所以就這麼做。 – korolar
'2017-12-03T10:15:30 + 01:00'是給定時區的'10:15:30'時間,或UTC時區的'09:15:30'(不是'16: 30')。時間已經在給定的時區。如果要刪除偏移量信息,請調用['toLocalDateTime()'](https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#toLocalDateTime--)以獲取'2017-12-03T10:15:30'。因爲這個問題是基於對[ISO日期格式](https://en.wikipedia.org/wiki/ISO_8601)的誤解而導致投票減少。 – Andreas
感謝您的幫助!我解決了我的問題! – paul590