要将String 转换为Date,您应该使用parse 方法。但是您使用的是 format 方法,它的作用正好相反(它将 Date 转换为 String)。
要检查 2 个 String 是否对应于同一日期,您必须使用 SimpleDateFormat 为每个日期解析它们。但是有两个细节要记住:
-
请注意,月份和星期几是英文,因此您应该使用java.util.Locale 来指明您要使用的语言。如果不指定,则使用系统默认,不保证始终为英文。
即使是这样,即使在运行时,也可以在不通知的情况下更改此配置,因此最好明确使用特定的配置。
-
第一个String 有时区信息:CDT - 我假设它是美国的中部夏令时间(尽管it could also be Cuba Daylight Time)。但是第二个String 没有任何时区信息,所以我假设它与第一个String 处于同一时区。
如果我不指定它,将使用系统的默认值,如果不是 CDT,它可能会给你不同的结果。与语言环境类似,默认值可以在不通知的情况下更改,即使在运行时也是如此,因此最好指定您正在使用的语言环境。
String s1 = "Wed May 18 00:00:00 CDT 2011";
String s2 = "May. 18, 2011";
// use English locale for month and day of week
SimpleDateFormat sdf1 = new SimpleDateFormat("E MMMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
SimpleDateFormat sdf2 = new SimpleDateFormat("MMMM. dd, yyyy", Locale.ENGLISH);
// set timezone, because String 2 has no timezone information
sdf2.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
// parse the dates
Date date1 = sdf1.parse(s1);
Date date2 = sdf2.parse(s2);
// compare them
boolean areDatesEqual = date1.equals(date2);
变量areDatesEqual 的值将是true(日期相同)。
请注意,我使用America/Chicago 作为时区名称。如果我使用了CDT,TimeZone 类将无法识别它并给出不正确的结果。
最好使用IANA timezones names(始终采用Region/City 的格式,例如America/Chicago 或Europe/London)。
避免使用三个字母的缩写(如CDT 或PST),因为它们是ambiguous and not standard。
有more than one timezone that uses CDT,因此您必须选择最适合您系统的那个。
您可以拨打TimeZone.getAvailableIDs()获取可用时区列表。
Java 新的日期/时间 API
旧的类(Date、Calendar 和 SimpleDateFormat)有 lots of problems 和 design issues,它们正在被新的 API 取代。
如果您使用的是 Java 8,请考虑使用 new java.time API。更简单,less bugged and less error-prone than the old APIs。
如果您使用的是 Java ,则可以使用 ThreeTen Backport,它是 Java 8 新日期/时间类的出色向后移植。对于Android,还有ThreeTenABP(更多关于如何使用它here)。
下面的代码适用于两者。
唯一的区别是包名(在 Java 8 中是 java.time,在 ThreeTen Backport(或 Android 的 ThreeTenABP)中是 org.threeten.bp),但类和方法 names 是相同的。
当您只比较日期(日/月/年)时,最好只使用这些字段而忽略其余字段(小时/分钟/秒和时区信息)。为此,您可以使用LocalDate 和DateTimeFormatter:
String s1 = "Wed May 18 00:00:00 CDT 2011";
String s2 = "May. 18, 2011";
// use English locale for month and day of week
DateTimeFormatter fmt1 = DateTimeFormatter.ofPattern("E MMMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
DateTimeFormatter fmt2 = DateTimeFormatter.ofPattern("MMMM. dd, yyyy", Locale.ENGLISH);
// parse the strings
LocalDate d1 = LocalDate.parse(s1, fmt1);
LocalDate d2 = LocalDate.parse(s2, fmt2);
// compare the dates
boolean areDatesEqual = d1.equals(d2);
由于LocalDate 只有日、小时和分钟(没有小时/分钟/秒,也没有时区信息),您无需关心在格式化程序中设置时区 - 尽管对英语语言环境的关注仍然存在.
结果也是true。