2014-10-16 53 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) { 

     } 

    } 
}