2011-08-18 95 views
4

这个问题是重复this question的意图。看起来大一点的是“被忽略”,而没有答案就是答案。java string to utc date

我需要用给定的日期模式/格式来解析给定的日期。

我有这样的代码,这是应该工作:

import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

public class Main 
{ 

    public static void main(String[] args) 
    { 
     final Date date = string_to_date("EEE MMM dd HH:mm:ss zzz yyyy", 
       "Thu Aug 14 16:45:37 UTC 2011"); 
     System.out.println(date); 
    } 

    private static Date string_to_date(final String date_format, 
      final String textual_date) 
    { 
     Date ret = null; 

     final SimpleDateFormat date_formatter = new SimpleDateFormat(
       date_format); 
     try 
     { 
      ret = date_formatter.parse(textual_date); 
     } 
     catch (ParseException e) 
     { 
      e.printStackTrace(); 
     } 

     return ret; 
    } 
} 

出于某种原因,我得到这样的输出:

java.text.ParseException: Unparseable date: "Thu Aug 14 16:45:37 UTC 2011" 
    at java.text.DateFormat.parse(DateFormat.java:337) 
    at Main.string_to_date(Main.java:24) 
    at Main.main(Main.java:10) 
null 

这有什么错我的约会模式?这似乎是一个谜。

+1

只需查看[SimpleDateFormat]的文档(http://download.oracle.com/javase/1.4.2/docs/api/java/text/ SimpleDateFormat.html) –

+0

我觉得新的日期('Thu Aug 14 16:45:37 UTC 2011');实际上作品 – Joe

+0

@True Soft我做了几次,但仍然无法弄清楚我需要的模式。为什么不把它写下来?我会appriciate它。 – Poni

回答

11

您的平台默认语言环境显然不是英语。 ThuAug是英文。您需要明确指定Locale2nd argument in the constructor of SimpleDateFormat

final SimpleDateFormat date_formatter = 
    new SimpleDateFormat(date_format, Locale.ENGLISH); // <--- Look, with locale. 

没有它,平台默认的区域将被用来代替解析日/月名称。您可以通过Locale#getDefault()了解你的平台默认语言环境的方式如下:

System.out.println(Locale.getDefault()); 
+0

很好的答案。从来没有想过要考虑EEE和MMM – Kal

+0

男人,你只是摇滚!这是问题。谢谢! – Poni

+0

不客气。 – BalusC

1

这应该解析给定的字符串。

public static void main(String[] args) throws ParseException 
{ 
    String sd = "Thu Aug 14 16:45:37 UTC 2011"; 


    String dp = "EEE MMM dd HH:mm:ss zzz yyyy"; 

    SimpleDateFormat sdf = new SimpleDateFormat(dp); 

    Date d = sdf.parse(sd); 

    System.out.println(d); 

} 
+0

不起作用。你测试过了吗? – Poni

+0

是的,我测试过,你得到了什么错误。只需要通知最后的sysout会在你的操作系统时区(不是UTC)打印日期。您可能必须使用SimplateDateFormat获取日期字符串,而不是默认时区。 – jatanp

+1

我得到'ParseException'。这很奇怪。代码是如此简单 - 没有地方的错字等'.. – Poni

0

我应该有指定一个区域,像这样:

final SimpleDateFormat date_formatter = new SimpleDateFormat(date_format, Locale.ENGLISH); 

由于BalusCgreat answer