我有一个看起来像这样的字符串
Aug 16, 2013,11:30:10
逗号可以替换为不同的分隔符,并且日期和时间位置可以切换。
我尝试将此格式用于我的 SimpleDateFormat(dtString 是上面的字符串):
Date d = null;
try {
d = new SimpleDateFormat("MMMM dd, yyyy,hh:mm:ss", Locale.ENGLISH).parse(dtString);
} catch (ParseException ex) {
Logger.getLogger(MonKaiClientImpl.class.getName()).log(Level.SEVERE, null, ex);
}
return d;
但是当我运行 d.getYear() 时,结果是113。
除 .getYear() 之外,所有其他 Date 方法都会返回正确的结果。我错过了什么吗?我的 SimpleDateFormatter 错了吗?
最佳答案
您不应该使用Date#getYear
。它已被弃用。
至于你得到的结果,它是在Javadoc中指定的:
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.
改用日历 API。或者更好的是,如果您可以使用第 3 方库,那么我真的建议您尝试 Joda Time 。或者等待明年 Java 8 的到来,它有一个新的日期时间 API。
关于java - 将字符串格式化为日期对象时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18277267/