gpt4 book ai didi

java - 为什么 SimpleDateFormat 会忽略语言环境?

转载 作者:搜寻专家 更新时间:2023-11-01 09:35:45 25 4
gpt4 key购买 nike

根据 javadoc,我可以创建一个可识别区域设置的 SimpleDateFormat
但是试试下面的代码:

Locale [] locales = {
Locale.GERMANY,
Locale.CANADA_FRENCH,
Locale.CHINA,
Locale.ITALIAN,
Locale.JAPANESE,
Locale.ENGLISH
};

try {
for(Locale locale : locales) {
final SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", locale);
System.out.println(myFormat.parse("2017-04-01 12:00:01"));

}
} catch (ParseException e) {
e.printStackTrace();
}

我在输出中看到:

Sat Apr 01 12:00:01 CEST 2017  
Sat Apr 01 12:00:01 CEST 2017
Sat Apr 01 12:00:01 CEST 2017
Sat Apr 01 12:00:01 CEST 2017
Sat Apr 01 12:00:01 CEST 2017
Sat Apr 01 12:00:01 CEST 2017

那么,为什么无论语言环境如何,日期格式都相同?

评论后更新:

for(Locale locale : locales) {  
System.out.println("Locale " + locale);
final SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", locale);
System.out.println(myFormat.parse("2017-04-01 12:00:01"));
System.out.println(myFormat.format(myFormat.parse("2017-04-01 12:00:01")));
System.out.println("-----------");

}

上面的代码 fragment 打印:

-----------  
Locale zh_CN
Sat Apr 01 12:00:01 CEST 2017
2017-04-01 12:00:01
-----------
Locale it
Sat Apr 01 12:00:01 CEST 2017
2017-04-01 12:00:01
-----------
Locale ja
Sat Apr 01 12:00:01 CEST 2017
2017-04-01 12:00:01
-----------
Locale en
Sat Apr 01 12:00:01 CEST 2017
2017-04-01 12:00:01

-----------

更新 2:
以下代码考虑了语言环境:

final SimpleDateFormat myFormat1 = new SimpleDateFormat("dd-MMM-yyyy");  
final SimpleDateFormat myFormat = new SimpleDateFormat("dd-MMM-yyyy", locale);
Date date = myFormat1.parse("05-Apr-2017");
String out = myFormat.format(date);
System.out.println(out);
System.out.println("-----------");

输出是:

Locale de_DE  
05-Apr-2017
-----------
Locale fr_CA
05-avr.-2017
-----------
Locale zh_CN
05-四月-2017
-----------
Locale it
05-apr-2017
-----------
Locale ja
05-4-2017
-----------
Locale en
05-Apr-2017
-----------

但这怎么会像(我)预期的那样工作呢?为什么yyyy-MM-dd HH:mm:ssdd-MMM-yyyy 的行为如此不同?

最佳答案

作为this answer discusses , Locale 没有正确的时区。因此,当您解析日期字符串时,将使用默认时区,这似乎是 CEST,即在中西部的某个地方。如果您改为将时区分配给您的 SimpleDateFormat,您将获得所需的行为:

String[] tzs = new String[]{
"Europe/Berlin",
"Canada/Eastern",
"Asia/Shanghai",
"Europe/Rome",
"Asia/Tokyo",
"America/New_York"
};

for (String tz : tzs) {
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz");
TimeZone timeZone = TimeZone.getTimeZone(tz);
myFormat.setTimeZone(timeZone);
System.out.println(myFormat.format(new Date()));
}

输出:

2017-04-11 09:52:42 CEST
2017-04-11 03:52:42 EDT
2017-04-11 15:52:46 CST
2017-04-11 09:52:47 CEST
2017-04-11 16:52:49 JST
2017-04-11 03:52:50 EDT

如果您想将日期字符串转换为时间戳,那么您可以通过 Java Date 对象。请注意,Java Date 没有时区,它只是一个任意时间点。

关于java - 为什么 SimpleDateFormat 会忽略语言环境?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43339124/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com