简体   繁体   English

如何使用SimpleDateFormat仅用月份和年份解析日期

[英]How to parse date with only month and year with SimpleDateFormat

I am working with expiration date of card. 我正在使用卡的到期日期。 I have a API where I will get expiration date in " yyMM " format as " String ". 我有一个API,在其中我将以“ yyMM ”格式获取“ String ”的到期日期。 Here I am trying to use 我在这里尝试使用

SimpleDateFormat with TimeZone.getTimeZone("UTC") 具有TimeZone.getTimeZone(“ UTC”)的SimpleDateFormat

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 现在的问题是,当我通过2011年时,给出的结果是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 . 在这里,您可以看到我将11月份作为月份传递,但它将其转换为Oct而不是Nov。

Why ? 为什么

And what other options I can use to convert string with yyMM to Date with Timezone? 还有什么其他选项可以用来将yyMM字符串转换为带时区的Date?

You should use the Java 8 YearMonth class. 您应该使用Java 8 YearMonth类。

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

You parsed it fine, but it's printed in PDT, your local timezone. 您解析得很好,但是它以本地时区PDT打印。

Sat Oct 31 17:00:00 PDT 2020

Well, Date doesn't track timezones. 好吧,日期不跟踪时区。 The Calendar class does, which is internal to the formatter. Calendar类可以,这在格式化程序内部。 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. 如果您将此输出逻辑地转换回UTC,由于PDT为UTC-7,它将是11月1日。

Basically, use java.time classes. 基本上,使用java.time类。 See additional information here How can I get the current date and time in UTC or GMT in Java? 在此处查看其他信息如何使用Java中的UTC或GMT获取当前日期和时间?

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

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