您似乎对解析和格式化感到困惑。
由于您在English 中输入日期字符串,您需要使用Locale.ENGLISH 进行解析,并且您需要另一个SimpleDateFormat 实例和Locale("pl", "PL") 格式化 获取到的java.util.Date对象与new Locale("pl", "PL")。
演示:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
Locale loc = new Locale("pl", "PL");
String date = "3 December 2020";
SimpleDateFormat sdfForParsing = new SimpleDateFormat("d MMMM yyyy", Locale.ENGLISH);
SimpleDateFormat sdfForFormatting = new SimpleDateFormat("d MMMM yyyy", loc);
sdfForParsing.setLenient(false);
try {
Date d = sdfForParsing.parse(date);
System.out.println(d);
String localiseByPolish = sdfForFormatting.format(d);
System.out.println(localiseByPolish);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
输出:
Thu Dec 03 00:00:00 GMT 2020
3 grudnia 2020
我相信您已经知道日期时间对象只存储日期时间信息*1不存储格式信息。在打印时,日期时间对象打印其类的 toString 实现返回的字符串。此外,java.util.Date 对象不代表真正的日期时间类,因为它只存储毫秒(例如,new Date() 对象是用来自January 1, 1970, 00:00:00 GMT 的毫秒数实例化的)并且当您打印它,它会计算 JVM 时区中的日期时间并打印相同的内容,即如果您在世界任何地方的给定时刻执行以下两行,
Date date = new Date();
System.out.println(date.getTime());
你会得到相同的号码。查看this answer 以获取演示。
java.util 的日期时间 API 和它们的格式化 API SimpleDateFormat 已经过时,并且由于有很多这样的 hack,它们很容易出错。建议完全停止使用它们并切换到modern date-time API。通过 Trail: Date Time 了解有关现代日期时间 API 的更多信息。
注意:如果您正在为一个 Android 项目工作,并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。
使用现代日期时间 API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
Locale loc = new Locale("pl", "PL");
String date = "3 December 2020";
DateTimeFormatter dtfForParsing = DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.ENGLISH)
.withResolverStyle(ResolverStyle.LENIENT);
DateTimeFormatter dtfForFormatting = DateTimeFormatter.ofPattern("d MMMM yyyy", loc);
LocalDate localeDate = LocalDate.parse(date, dtfForParsing);
System.out.println(localeDate);
String localiseByPolish = localeDate.format(dtfForFormatting);
System.out.println(localiseByPolish);
}
}
输出:
2020-12-03
3 grudnia 2020
*1modern date-time API 还存储时区信息。查看Overview 了解有关这些课程的更多信息。