2014-10-16 54 views
0

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

+2

您解析它在UTC时区,然后格式化结果,如果你在本地时区需要。你为什么试图做到这一点?你能够使用Joda Time或Java 1.8吗? – 2014-10-16 16:34:34

+0

谢谢,这是我需要的。 :-)我知道乔达时间是更好的解决方案,但我需要解决它,没有它。 – 2014-10-16 16:39:20

+1

您应该在问题中指定您的需求 - Java中有三种不同的“非常流行的”日期/时间库:java.util.Calendar/Date,Joda Time和java.time。如果您在使用方面受到限制,请尽量避免浪费时间。 – 2014-10-16 16:50:35

回答

2

您可以使用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 
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) { 

     } 

    } 
}