日期格式为 8 月 14 日至 YYYYMMDD

发布于 2024-10-20 16:28:27 字数 108 浏览 0 评论 0原文

将日期 2011 年 8 月 14 日更改为格式 20110814 ..我如何在 java 中做到这一点?

这里 14aug 是一个字符串... String date="14aug";

Change the date 14 aug 2011 to the format 20110814 .. how can i do that in java ?

Here 14aug is a string ... String date="14aug";

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

幼儿园老大 2024-10-27 16:28:28
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String yyyyMMdd = sdf.format(date);

参考:java.text.SimpleDateFormat

更新:精英绅士的问题很重要。如果您从 String 开始,那么您应该首先解析它以从上面的示例中获取 date 对象:

Date date = new SimpleDateFormat("dd MMM yyyy").parse(dateString);
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String yyyyMMdd = sdf.format(date);

Reference: java.text.SimpleDateFormat

Update: the question by The Elite Gentleman is important. If you start with a String, then you should first parse it to obtain the date object from the above example:

Date date = new SimpleDateFormat("dd MMM yyyy").parse(dateString);
时光病人 2024-10-27 16:28:28

其他答案是2011年写的时候的好答案。时间继续前进。如今,没有人应该使用早已过时的类 SimpleDateFormatDate。现代的答案使用 java.time 类:

    String date = "14 aug 2011";
    DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("dd MMM uuuu")
            .toFormatter(Locale.ENGLISH);
    System.out.println(LocalDate.parse(date, parseFormatter)
                        .format(DateTimeFormatter.BASIC_ISO_DATE));

这会打印出所需的内容:

20110814

现代解析机制有些更严格,因为经验表明旧的解析机制过于宽松,并且经常在需要的情况下产生令人惊讶的结果预计会出现错误消息。例如,现代的需要正确的大小写,即英语中 Aug 的大写 A,除非我们告诉它应该在不区分大小写的情况下进行解析。这就是我使用 parseCaseInsensitive() 所做的事情。该调用会影响后续构建器方法调用,因此我们必须将其放在之前 appendPattern()

编辑:从问题中逐字提取字符串 "14aug"SimpleDateFormat 会使用 1970 作为默认年份(纪元年份),这会给您带来如何获取正确年份的麻烦。现代类允许您显式指定默认年份,例如:

    String date = "14aug";
    DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("ddMMM")
            .parseDefaulting(ChronoField.YEAR, Year.now(ZoneId.systemDefault()).getValue())
            .toFormatter(Locale.ENGLISH);

通过此更改,今天运行代码我们得到:

20170814

编辑 2:现在使用 DateTimeFormatter.BASIC_ISO_DATE 进行格式化,如 Basil Bourque 的回答

The other answers were good answers in 2011 when they were written. Time moves on. Today no one should use the now long outdated classes SimpleDateFormat and Date. The modern answer uses the java.time classes:

    String date = "14 aug 2011";
    DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("dd MMM uuuu")
            .toFormatter(Locale.ENGLISH);
    System.out.println(LocalDate.parse(date, parseFormatter)
                        .format(DateTimeFormatter.BASIC_ISO_DATE));

This prints the desired:

20110814

The modern parsing mechanism is somewhat stricter because experience shows that the old one was way too lenient and often produced surprising results in situations where one would have expected an error message. For example, the modern one requires correct case, that is, capital A in Aug in English, unless we tell it that it should parse without case sensitivity. So this is what I am doing with the parseCaseInsensitive(). The call affects the following builder method calls, so we have to place it before appendPattern().

Edit: Taking your string "14aug" from the question literally. SimpleDateFormat would have used 1970 as default year (year of the epoch), giving you trouble how to get the correct year. The modern classes allow you to specify a default year explicitly, for example:

    String date = "14aug";
    DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("ddMMM")
            .parseDefaulting(ChronoField.YEAR, Year.now(ZoneId.systemDefault()).getValue())
            .toFormatter(Locale.ENGLISH);

With this change, running the code today we get:

20170814

Edit 2: Now using DateTimeFormatter.BASIC_ISO_DATE for formatting as recommended in Basil Bourque’s answer.

空城旧梦 2024-10-27 16:28:28

虽然 Bozho 给出的示例适用于英语语言环境,但它可能不适用于其他语言环境(只要 "aug" 不是其他语言环境中的月份名称)。对于具有波兰语言环境的环境,我宁愿使用类似的内容:

ParsePosition pos = new ParsePosition(0);
Date date = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH).parse("14 aug 2011", pos);

另请注意 ParsePosition 的使用,以防出现解析问题(然后 date 将是 null >) 会告诉您解析在什么位置出现问题。

While example given by Bozho is good for English locale it may not work in other locales (as long as "aug" is not month name in other locale). For my environment with Polish locales I would rather use something like:

ParsePosition pos = new ParsePosition(0);
Date date = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH).parse("14 aug 2011", pos);

Also note usage of ParsePosition which in case of parse problems (then date will be null) will tell you at what position parsing had troubles.

一指流沙 2024-10-27 16:28:28

Ole VV 的回答非常好。它向您展示了使用 java.time 类的现代方法,而不是麻烦的旧式日期时间类( DateCalendar )。

MonthDay

我将通过添加一个想法来扩展该答案:您可以将您输入的月份数字和缩写月份名称表示为 MonthDay 对象。

要了解此处 DayeTimeFormatterBuilder 的使用,请参阅其他 Ole VV 的回答

String input = "11aug" ;
DateTimeFormatter f = 
    new DateTimeFormatterBuilder()  
        .parseCaseInsensitive()
        .appendPattern( "ddMMM" )
        .toFormatter( Locale.ENGLISH )
;
MonthDay md = MonthDay.parse( input , f ) ;

md.toString(): --08-11

如果可能,我建议使用 ISO 8601 标准格式 --MM-DD 来以文本方式表示月日值,而不是您自己的自定义非-标准格式。包括 MonthDay 在内的 java.time 类在解析和生成字符串时默认使用标准格式,因此无需指定格式模式。解析:MonthDay md = MonthDay.parse( "--08-11" ) ;

通过指定所需年份生成仅日期值。具体来说,是一个 LocalDate 对象。

LocalDate ld = md.atYear( 2011 ) ; 

ld.toString(): 2011-08-11

您所需的输出格式恰好符​​合标准 ISO 8601 格式。您的格式是“基本”版本,最大限度地减少了分隔符的使用。此格式已在 DateTimeFormatter.BASIC_ISO_DATE

String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE ) ;

20110811

The Answer by Ole V.V. is excellent. It shows you the modern approach using java.time classes rather than the troublesome old legacy date-time classes ( Date & Calendar ).

MonthDay

I will extend that Answer by adding one thought: You can represent your input of day-of-month number and abbreviated Month name as a MonthDay object.

To understand the use of DayeTimeFormatterBuilder here, see that other Answer by Ole V.V..

String input = "11aug" ;
DateTimeFormatter f = 
    new DateTimeFormatterBuilder()  
        .parseCaseInsensitive()
        .appendPattern( "ddMMM" )
        .toFormatter( Locale.ENGLISH )
;
MonthDay md = MonthDay.parse( input , f ) ;

md.toString(): --08-11

If possible, I suggest using the ISO 8601 standard format --MM-DD for textually representing a month-day value, rather than your own custom non-standard format. The java.time classes including MonthDay use the standard formats by default when parsing and generating strings, so no need to specify a formatting pattern. To parse: MonthDay md = MonthDay.parse( "--08-11" ) ;.

Generate a date-only value by specifying your desired year. Specifically, a LocalDate object.

LocalDate ld = md.atYear( 2011 ) ; 

ld.toString(): 2011-08-11

Your desired output format happens to comply with the standard ISO 8601 formats. Your format is the “Basic” version that minimizes the use of separators. This format is already defined in DateTimeFormatter.BASIC_ISO_DATE.

String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE ) ;

20110811

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文