UTC字符串日期到本地日期

时间:2014-10-16 16:31:16

标签: java date

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

2 个答案:

答案 0 :(得分:3)

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

此函数将根据char序列(您的日期)和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

答案 1 :(得分:1)

试试这个:

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

        }

    }
}