在Year字段中用两位数转换日期时出错 [英] Error converting date with two digits for the Year field

查看:65
本文介绍了在Year字段中用两位数转换日期时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// input format: dd/MM/yy
SimpleDateFormat parser = new SimpleDateFormat("dd/MM/yy");
// output format: yyyy-MM-dd
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(formatter.format(parser.parse("12/1/20"))); // 0020-11-01

我正在使用上面的代码,但是它给我的年份是'0020'而不是'2020'.

I am using the above code but it is giving me year as '0020' instead of '2020'.

推荐答案

为此使用 java.time :

public static void main(String[] args) {
    String dateString = "12/1/20";
    LocalDate localDate = LocalDate.parse(dateString, DateTimeFormatter.ofPattern("dd/M/yy"));
    System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}

输出为

2020-01-12

请注意模式中的 M 数量,您无法使用双 M 解析包含一个数字一个月的 String .代码>这里.

Pay attention to the amount of M in the patterns, you cannot parse a String that contains a single digit for a month using a double M here.

这篇关于在Year字段中用两位数转换日期时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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