java - 如何设置 java.util.Date 的偏移量?

标签 java date datetime datetime-format

我有一个字符串形式的日期 - 15Sep20162040,我必须将其格式化为另一种格式,时区为 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

我怎样才能实现它?

最佳答案

您可以使用SimpleDateFormatsetTimeZone方法,如下所示:

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);
    }
}

如果您只想更改结果末尾的时区,请尝试以下操作:

    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 - 如何设置 java.util.Date 的偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39557374/

相关文章:

SQL服务器: Get total days between two dates

c# - Asp.net 比较验证器以验证日期

javascript - 类型错误 : variable. getHours();未定义,其中变量 = Date.now()?

java - 如何解决 android.os.NetworkOnMainThreadException?

java - 如何从数组中找到最接近的值?

java - 如何连接到独立的 HSQLDB

date - 解析日期上的 Elasticsearch 异常

java - 为什么将 "0000:00:00 00:00:00"解析为日期返回 -0001-11-28T00 :00:00Z?

c# - Xamarin 'iOS Foundation NSDate to C# DateTime conversion' 反之亦然不考虑夏令时

java - 如何递归地循环遍历 ZipEntry