SimpleDateFormat时区和语言环境

对于类似于”20/Nov/2015:12:59:59 +0800”的字符串,怎么用SimpleDateFormat进行转换?

最近做的一个项目中,涉及对日志的解析,其中有个字段是时间,形如”20/Nov/2015:12:59:59 +0800”,要将这个字段转换为时间戳。
向普通的”2015-11-20 12:59:59”自不必说它,其中”+0800”是时区字段,用Z即可。
但是对于月份字段,在java api中有介绍

Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.

所以此处用三个M来表示月份,总体就使用dd/MMM/yyyy:HH:mm:ss Z进行解析。

1
2
3
String str = "20/Nov/2015:12:59:59 +0800";
SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z");
Date date = df.parse(str);

但是实际过程中竟然报错:

1
2
java.text.ParseException: Unparseable date: "20/Nov/2015:12:59:59 +0800"
at java.text.DateFormat.parse(DateFormat.java:366)

无奈之下,只能先format一下,看看出来什么内容。

1
2
3
String str = "20/Nov/2015:12:59:59 +0800";
SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z");
System.out.println(df.format(new Date()));

结果是

1
21/十一月/2015:22:54:26 +0800

原来是语言环境没有设置,只需要在构造SimpleDateFormat时设置locale为us即可。

SimpleDateFormat(String pattern, Locale locale)
Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the given locale.

1
2
3
String str = "20/Nov/2015:12:59:59 +0800";
SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.US);
Date date = df.parse(str);

其他一些pattern和示例都可以去java api官网查看。
http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html