java tostring格式化日期,应该使用哪种模式来解析java.util.Date的toString返回的日期字符串?...

While looking at this question, I discovered that both the OP's and the accepted answer's code, when run, produce a ParseException. Here is the code:

String dateString = new java.util.Date().toString();

System.out.println(dateString);

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");

Date date = format.parse(dateString);

System.out.println(date.toString());

After closely examining how the date string printed differs with the format provided, I still can't find why they don't match. Here is the date string printed:

Sat Aug 19 18:58:41 BST 2017

My instincts tell me that the reason why this does not work is that my locale is different - Locale.getDefualt() returns ja_JP.

解决方案

The pattern does not matter, but the locale does.

Date#toString uses Locale.US and English names for days, months and time zones, while SimpleDateFormat(String) uses your default locale (specifically: Locale.getDefault(Locale.Category.FORMAT)). If those two locales do not match, parsing may fail as the local names are not guaranteed to match.

So you should be fine with

new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);

Excerpts from JDK 8:

SimpleDateFormat:

public SimpleDateFormat(String pattern)

{

this(pattern, Locale.getDefault(Locale.Category.FORMAT));

}

Date:

public String toString() {

// "EEE MMM dd HH:mm:ss zzz yyyy";

BaseCalendar.Date date = normalize();

StringBuilder sb = new StringBuilder(28);

int index = date.getDayOfWeek();

if (index == BaseCalendar.SUNDAY) {

index = 8;

}

convertToAbbr(sb, wtb[index]).append(' '); // EEE

convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM

CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH

CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm

CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss

TimeZone zi = date.getZone();

if (zi != null) {

sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz

} else {

sb.append("GMT");

}

sb.append(' ').append(date.getYear()); // yyyy

return sb.toString();

}

[...]

private final static String wtb[] = {

"am", "pm",

"monday", "tuesday", "wednesday", "thursday", "friday",

"saturday", "sunday",

"january", "february", "march", "april", "may", "june",

"july", "august", "september", "october", "november", "december",

"gmt", "ut", "utc", "est", "edt", "cst", "cdt",

"mst", "mdt", "pst", "pdt"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值