简体   繁体   English

在将字符串格式化为日期对象时遇到麻烦

[英]Having trouble format a string into a date object

I have a string that looks like this 我有一个看起来像这样的字符串

Aug 16, 2013,11:30:10

The comma can be replaced by a different separator and the date & time position can be switched. 逗号可以用其他分隔符代替,日期和时间位置也可以切换。

I am trying to use this format for my SimpleDateFormat(dtString is the String above): 我正在尝试将这种格式用于我的SimpleDateFormat(dtString是上面的String):

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;

but when I run d.getYear() the result is 113 . 但是当我运行d.getYear()时,结果是113

All of the other Date methods return the correct result except .getYear(). 除.getYear()外,所有其他Date方法都返回正确的结果。 Am I missing something? 我想念什么吗? Is my SimpleDateFormatter wrong? 我的SimpleDateFormatter错误吗?

You should not use Date#getYear . 您不应使用Date#getYear It's deprecated. 不推荐使用。

As for the result you get, it's as specified in the Javadoc: 至于得到的结果,它是在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. 返回一个值,该值是从包含或由此日期对象表示的时间点开始的年份中减去1900的结果,如当地时区所解释。

Use Calendar API instead. 请改用Calendar API。 Or even better, if you can use 3rd party library, then I would really suggest you to try Joda Time . 甚至更好的是,如果您可以使用3rd party库,那么我真的建议您尝试Joda Time Or wait for Java 8 to come next year, that has a new Date Time API. 或等待具有新的Date Time API的Java 8明年发布。

Simple way to check the result of SimpleDateFormat parsing is this 检查SimpleDateFormat解析结果的简单方法是这样

System.out.println(d);

and it shows correct result 它显示正确的结果

Fri Aug 16 11:30:10 EEST 2013

the problems is that Date methods interpreting year, month, day, hour, minute, and second are deprecated. 问题在于不赞成使用日期方法来解释年,月,日,小时,分钟和秒。 See Date API 请参阅日期API

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM