如何使用SimpleDateFormat仅用月份和年份解析日期 [英] How to parse date with only month and year with SimpleDateFormat

查看:520
本文介绍了如何使用SimpleDateFormat仅用月份和年份解析日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理卡的到期日期。我有一个API,在其中我将以 字符串的格式获取 yyMM 格式的到期日期。在这里,我尝试使用

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和TimeZone.getTimeZone( UTC)

SimpleDateFormat with TimeZone.getTimeZone("UTC")

所以我的代码就像

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

现在的问题是,当我经过2011年时,给出的结果是 Sat 10月31日17:00:00 PDT 2020

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

在这里您可以看到我作为月份通过了 11 ,但是正在将其转换为 Oct ,而不是 Nov

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

为什么

还有什么我可以用来转换字符串的选项 yyMM 到时区的日期?

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

推荐答案

您解析得很好,但它以您当地的时区PDT打印。

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

Sat Oct 31 17:00:00 PDT 2020

好吧,日期不跟踪时区。 Calendar 类执行此操作,这是格式化程序的内部功能。但是,默认的打印行为是当前时区。

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

如果您将此输出逻辑地转换回UTC,由于PDT为UTC-7,因此它将是11月1日。

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

基本上,使用 java.time 类。在此处查看其他信息如何获取Java中UTC或GMT的当前日期和时间?

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

这篇关于如何使用SimpleDateFormat仅用月份和年份解析日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆