按照月份名称优先的格式获取日期 [英] Getting the date as per the format in which month name is coming as first

查看:46
本文介绍了按照月份名称优先的格式获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以如下所示的格式获取字符串

I am getting the string in this formatas shown below

03-12-2018

我想按照Java 8标准将其转换为以下格式,请告知

I want to convert this into as below format as per Java 8 standards please advise

December 03 , 2018  

下面显示了我尝试过的方法,但是我没有成功,请告知如何达到相同的目的

what I have tried is shown below but i was not succeessful , please advise how to acheieve the same

SimpleDateFormat month_date = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    String actualDate = "03-12-2018";

    Date date = sdf.parse(actualDate);

    String month_name = month_date.format(date);
    System.out.println("Month :" + month_name);  

推荐答案

java.time

    DateTimeFormatter originalFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
    DateTimeFormatter monthFirst = DateTimeFormatter
            .ofLocalizedDate(FormatStyle.LONG)
            .withLocale(Locale.ENGLISH);

    String actualDate = "03-12-2018";
    LocalDate date = LocalDate.parse(actualDate, originalFormatter);
    String monthName = date.format(monthFirst);
    System.out.println("Month :" + monthName);

输出:

月份:2018年12月3日

Month :December 3, 2018

由于您使用的是Java 8(即使您没有使用Java 8),也请避免使用过长且臭名昭著的 SimpleDateFormat 类.尽可能使用内置格式,而不要滚动自己的格式.

Since you are using Java 8 (and even if you didn’t), avoid the long outdated and notoriously troublesome SimpleDateFormat class. Use the built in formats where you can rather than rolling your own.

您解析了格式为 yyyy-MM-dd 03-12-2018 字符串.因此,这解析为公元3年(第12年)第12个月的第2018天(即2015年之前).显然,十二月没有2018年的日子.因此,期待有一个例外将是公平的.这只是 SimpleDateFormat 造成麻烦的点之一:使用标准设置,它只会继续计数接下来的几个月和几年的天数,直到6年9月9日(即5年半)结束.之后.接下来,您使用包括月份名称和年份在内的格式化程序对该日期进行了格式化,似乎您忘记了月份中的日期.无论如何,它都打印为 Jun 0009 (您应该在问题中告诉我们,以便我们可以找出问题所在;此信息对尝试解决您的问题非常有帮助).

You parsed a string of 03-12-2018 with a format of yyyy-MM-dd. So this parses into the 2018th day of the 12th month of year 3 CE (2015 years ago). There obviously weren’t 2018 days in December. So it would have been fair to expect an exception. This is just one of the points where SimpleDateFormat is troublesome: with standard settings it just keeps counting days into the following months and years and ends up at June 9 year 9, that is, 5 and a half years later. Next you formatted this date with a formatter including month name and year, it seems you had forgot the day of month. Anyway it printed as Jun 0009 (which you should have told us in your question so that we could see what was wrong; this information can be very helpful in trying to solve your problem).

Oracle教程:日期时间解释了如何使用 java.时间.

这篇关于按照月份名称优先的格式获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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