【问题标题】:How to convert and format a UTC datetime to local time如何将 UTC 日期时间转换为本地时间并将其格式化
【发布时间】:2015-08-19 20:48:42
【问题描述】:

我的程序将 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

请指教。

【问题讨论】:

  • 我推荐你找Joda Time Library...
  • 阅读documentation。如果你有 Java 8 切换到java.time,但你仍然需要编写自己的格式化程序。
  • 您为什么期望“01:00:14”的时间?如果您想要 EDT 时间,我希望您想要“01:30:00”来匹配未格式化的输出。

标签: java datetime


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 2021-10-14
    相关资源
    最近更新 更多