【问题标题】:UTC string date to local dateUTC 字符串日期到本地日期
【发布时间】:2014-10-17 01:20:33
【问题描述】:

您好,我从第三方 REST 服务获取日期,格式为 2014-10-14 03:05:39 等字符串,格式为 UTC。如何将此日期转换为本地格式?

【问题讨论】:

  • 你在 UTC 时区解析它,然后如果你需要在本地时区格式化结果。为了做到这一点,你做了什么尝试?你可以使用 Joda Time 或 Java 1.8 吗?
  • 谢谢,这正是我所需要的。 :-) 我知道 joda time 是更好的解决方案,但没有它我需要解决它。
  • 您应该在问题中指定您的要求 - Java 中有三个不同的“非常流行”的日期/时间库:java.util.Calendar/Date、Joda Time 和 java.time。如果您在使用方面受到限制,请尽早明确该限制以避免浪费人们的时间。

标签: java date


【解决方案1】:

您可以使用 LocalDate (Java 1.8) 和函数 LocalDateTime.parse

此函数将根据字符序列(您的日期)和 DateTimeFormatter 返回一个 LocalDateTime 对象。

来自 Java 1.8 API:

public static LocalDateTime parse(CharSequence text,
                                  DateTimeFormatter formatter)

Obtains an instance of LocalDateTime from a text string using a specific formatter.
The text is parsed using the formatter, returning a date-time.

Parameters:
text - the text to parse, not null
formatter - the formatter to use, not null
Returns:
the parsed local date-time, not null
Throws:
DateTimeParseException - if the text cannot be parsed

【讨论】:

    【解决方案2】:

    试试这个:

    import java.util.*;
    import java.text.*;
    public class Tester {
        public static void main(String[] args){
            try {
             String utcTimeString = "2014-10-14 03:05:39";
    
             DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
             utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
             Date utcTime = utcFormat.parse(utcTimeString);
    
    
             DateFormat localFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
             localFormat.setTimeZone(TimeZone.getDefault());
             System.out.println("Local: " + localFormat.format(utcTime));
    
            } catch (ParseException e) {
    
            }
    
        }
    }
    

    【讨论】:

    • 请不要有空的 catch 块。不好的做法。
    猜你喜欢
    • 2018-09-27
    • 1970-01-01
    • 2015-05-07
    • 2021-04-19
    • 2014-02-22
    • 2016-02-25
    • 2011-06-13
    • 2020-02-03
    • 2012-10-29
    相关资源
    最近更新 更多