如何设置java.util.Date的偏移量? [英] How to set offset of a java.util.Date?
问题描述
我有一个日期作为字符串- 15Sep20162040
,我必须将其格式化为时区为 2016-09-15T20的另一种格式: 40:00 + 0400
。
I have a Date as a String - 15Sep20162040
, which I have to format it into another format with Timezone as 2016-09-15T20:40:00+0400
.
我做了如下操作:
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateFormatExample {
private static SimpleDateFormat offsetDateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssZ");
private static SimpleDateFormat dateFormatter = new SimpleDateFormat(
"ddMMMyyyyHHmm");
public static void main(String[] args) throws ParseException {
String date = "15Sep20162040";
String result = offsetDateFormat.format(dateFormatter.parse(date));
System.out.println(result); // 2016-09-15T20:40:00+0400
}
}
现在,我必须根据时区差异来修改输出,例如,如果差异为 +0100
,则输出应类似于: 2016-09-15T20:40:00 + 0100
,如果差异为 -0200
,则输出应类似于: 2016-09-15T20:40:00-0200
。
Now, I have to modify the output based on timezone difference, for example if difference is +0100
, output should resemble as: 2016-09-15T20:40:00+0100
and if difference is -0200
, output should resemble as: 2016-09-15T20:40:00-0200
.
我该如何实现?
推荐答案
您可以将 SimpleDateFormat
的 setTimeZone
方法用作下面:
You can use SimpleDateFormat
's setTimeZone
method as below:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class DateFormatExample {
private static SimpleDateFormat offsetDateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ssZ");
private static SimpleDateFormat dateFormatter = new SimpleDateFormat(
"ddMMMyyyyHHmm");
public static void main(String[] args) throws ParseException {
String date = "15Sep20162040";
String result = offsetDateFormat.format(dateFormatter.parse(date));
System.out.println(result); // 2016-09-15T20:40:00+0400
offsetDateFormat.setTimeZone(TimeZone.getTimeZone("GMT-8:00"));
result = offsetDateFormat.format(dateFormatter.parse(date));
System.out.println(result);
}
}
如果您只想在最后更改时区结果
的值,请尝试以下操作:
If you simply want to change the timezone at the end of result
, please try the following:
String offset = "GMT-8:00";
String date = "15Sep20162040";
date = date+" "+offset;
SimpleDateFormat dateFormatter2 = new SimpleDateFormat("ddMMMyyyyHHmm Z");
SimpleDateFormat offsetDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
offsetDateFormat2.setTimeZone(TimeZone.getTimeZone(offset));
String result = offsetDateFormat2.format(dateFormatter2.parse(date));
System.out.println(result);
希望这会有所帮助。
这篇关于如何设置java.util.Date的偏移量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!