How to parse date with only month and year with SimpleDateFormat

微笑、不失礼 提交于 2019-12-11 16:11:22

问题


I am working with expiration date of card. I have a API where I will get expiration date in "yyMM" format as "String". Here I am trying to use

SimpleDateFormat with TimeZone.getTimeZone("UTC")

So my code is like

String a= "2011";
SimpleDateFormat formatter = new SimpleDateFormat("yyMM");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = formatter.parse(a);
System.out.println(date);

Now problem is, when I am passing 2011 the out it gives is Sat Oct 31 17:00:00 PDT 2020

Here you can see I am passing 11 as month but it is converting it to Oct instead of Nov.

Why?

And what other options I can use to convert string with yyMM to Date with Timezone?


回答1:


You parsed it fine, but it's printed in PDT, your local timezone.

Sat Oct 31 17:00:00 PDT 2020

Well, Date doesn't track timezones. The Calendar class does, which is internal to the formatter. But still, default print behavior is current timezone.

If you logically convert this output back to UTC, and it will be November 1 since PDT is UTC-7.

Basically, use java.time classes. See additional information here How can I get the current date and time in UTC or GMT in Java?




回答2:


You should use the Java 8 YearMonth class.

String a = "2011";
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("yyMM");
YearMonth yearMonth = YearMonth.parse(a, inputFormat);

DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("MMMM yyyy");
System.out.println(yearMonth.format(outputFormat));

Output

November 2020



来源:https://stackoverflow.com/questions/46780340/how-to-parse-date-with-only-month-and-year-with-simpledateformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!