如何转换日期值“2017年5月26日”至“26/05 / 2017”? [英] How to convert the date value "26th May 2017" to "26/05/2017"?

查看:231
本文介绍了如何转换日期值“2017年5月26日”至“26/05 / 2017”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何java库可用于解析语言特定的序数指示符/后缀?

Is there any java library available to parse language specific ordinal indicator/suffix?

我有如下日期值: 5月26日2017 。我想将其转换为 26/05/2017 。有人可以指导我怎么做吗?

I have a date value like the following: 26th May 2017. I want to convert this to 26/05/2017. Could anyone please guide me how to do?

推荐答案

你可以直接将这种格式解析为Java 8 LocalDate 使用自定义日期格式:

You can parse this format directly to a Java 8 LocalDate using a custom date format:

static final Map<Long, String> ORDINAL_DAYS = new HashMap<>();
static
 {
   ORDINAL_DAYS.put(1, "1st");
   .... more ....
   ORDINAL_DAYS.put(26, "26th");
   .... more ....
   ORDINAL_DAYS.put(31, "31st");
 }

static final DateTimeFormatter FORMAT_DAY_MONTH_YEAR = new DateTimeFormatterBuilder()
  .appendText(ChronoField.DAY_OF_MONTH, ORDINAL_DAYS)
  .appendLiteral(' ')
  .appendText(ChronoField.MONTH_OF_YEAR)
  .appendLiteral(' ')
  .appendText(ChronoField.YEAR)
  .toFormatter();


 String dateInString = "26th May 2017";

 LocalDate date = LocalDate.parse(dateInString, FORMAT_DAY_MONTH_YEAR);

这是使用 DateTimeFormatter.appendText 接受用于映射日期字符串的地图。

This is using the version of DateTimeFormatter.appendText which accepts a map that is used to map the day string.

为了简洁起见,我需要填写 ORDINAL_DAYS 中遗漏的所有条目。

You will need to fill in all the missing entries in ORDINAL_DAYS that I have left out for brevity.

这篇关于如何转换日期值“2017年5月26日”至“26/05 / 2017”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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