如何将UTC日期时间转换并格式化为本地时间

时间:2015-08-19 20:48:42

标签: java datetime

我的程序将UTC时间转换为本地时间,但不是我想要的格式。我从以下链接Convert UTC to current locale time

中举了一个例子
 public static void main(String[] args) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date myDate = simpleDateFormat.parse("2015-08-19 05:30:00.049 UTC+0000");
        System.out.println("**********myDate:" + myDate);
    }

输出:

**********myDate:Wed Aug 19 01:30:00 EDT 2015

我的预期输出格式为:

2015-08-19 01:00:14

请告知。

1 个答案:

答案 0 :(得分:6)

您已成功将文本解析为日期:

Date myDate = simpleDateFormat.parse("2015-08-19 05:30:00.049 UTC+0000");

然而,您接着开始打印myDate.toString()

System.out.println("**********myDate:" + myDate);

您不会以这种方式获得预期的格式。使用(另一个)SimpleDateFormat以您希望的方式格式化myDate

final SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm")
outputFormat.setTimeZone(TimeZone.getTimeZone("EDT"));
System.out.println("**********myDate:" + ouputFormat.format(myDate));