如何在Java中将模式dd-MMM-yy的字符串日期值转换为模式dd/MM/yyyy的Date对象 [英] how to convert a String date value of pattern dd-MMM-yy to Date object of Pattern dd/MM/yyyy in java

查看:70
本文介绍了如何在Java中将模式dd-MMM-yy的字符串日期值转换为模式dd/MM/yyyy的Date对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有

String dateAsString = "15-May-84";

,我想将其转换为

Date date = 15/05/1984;

第一次尝试

new SimpleDateFormat("dd/MM/yyyy").format(new Date(dateAsString )), "dd/MM/yyyy")

第二次尝试

LocalDate.parse(dateAsString , DateTimeFormatter.ofPattern("dd/MM/uuuu")));

我尝试过使用 SimpleDateFormat LocalDate 的多种方法,但是它总是返回15/05/0084.

I tried many ways with SimpleDateFormat and LocalDate but it's always returning 15/05/0084.

任何人都可以在这里帮助

can anyone help here please

推荐答案

首先,为什么不能将year作为两位数字用作字符串,为什么?

First of all, it's not good to use year as two digits as a string, Why?

要解析日期,这很容易,您可以使用:

to parse your date, it is easy, you can use:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yy")
        .withLocale(Locale.US);

LocalDate ld = LocalDate.parse("15-May-84", formatter);

但是

这将返回 2084-05-15 ,我认为您不是在看这个,而是在 1984-05-15 .

But

This will return 2084-05-15, which I think you are not looking to this, but you look to 1984-05-15.

因此,您可以使用 minusYears(100):

LocalDate ld = LocalDate.parse("15-May-84", formatter).minusYears(100);

但是

20年5月15日等其他年份可能会出现问题,该年份将返回 1920-05-15 .

But

Which can be a problem to other years like 15-May-20 which will return 1920-05-15.

为此,我完全不建议您将年份中的两位数用作字符串.

For that I don't advice at all to use two digits in your year as a string.

除非

除非您再次确认您的日期在 1900 1999 之间,或者在 2000 2999 之间.在这种情况下,您可以创建一个(安全的)自定义解析器!

Unless

unless you have another confirmation that your date is between 1900 and 1999, or between 2000 and 2999. in this case you can create a (safe) custom parser!

不使用旧版Date库,而仅使用现代的 java.time API

Don't use the legacy Date library, instead use only the modern java.time API

这篇关于如何在Java中将模式dd-MMM-yy的字符串日期值转换为模式dd/MM/yyyy的Date对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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