SimpleDateFormat-格式-月份9月-JDK16 [英] SimpleDateFormat - format - Month September - JDK16

查看:55
本文介绍了SimpleDateFormat-格式-月份9月-JDK16的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚将Java从JDK-15升级到JDK-16,在使用SimpleDateFormat转换Date时看到一个问题。使用yyyy-MMM-dd设置格式时,仅9月月份就提供了4个字符,而不是3个字符。

例如:2021-Sep-11显示为2021-Sept-11

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 150);
    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MMM-dd");
    System.out.println(cal.getTime());

    String formatted = format1.format(cal.getTime());
    System.out.println(formatted);

在我看来像是个虫子。我在发布说明中看不到这方面的任何更新。有谁遇到过类似的问题吗?在JDK-15之前工作正常。

推荐答案

如果没有Locale,请不要使用日期-时间格式/分析类型,因为文本是Locale敏感的。

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 150);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MMM-dd", Locale.ENGLISH);
        System.out.println(cal.getTime());

        String formatted = format1.format(cal.getTime());
        System.out.println(formatted);
    }
}

输出:

2021-Sep-11
请注意,java.util日期-时间API及其格式化APISimpleDateFormat已过时且容易出错。建议完全停止使用,切换到java.timemodern date-time API*

使用现代日期-时间API:

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Change ZoneId as per your requirement e.g. ZoneId.of("Europe/London")
        LocalDate date = LocalDate.now(ZoneId.systemDefault());
        date = date.plusDays(150);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MMM-dd", Locale.ENGLISH);
        String formatted = dtf.format(date);
        System.out.println(formatted);
    }
}

输出:

2021-Sep-11

选中this answer以了解有关uy的更多信息。

Trail: Date Time了解有关现代日期-时间API的更多信息。


*出于任何原因,如果您必须坚持使用Java 6或Java 7,您可以使用ThreeTen-Backport,它将大部分java.time功能移植到Java 6&;7。如果您正在为Android项目工作,而您的Android API级别仍然不符合Java-8,请勾选Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

这篇关于SimpleDateFormat-格式-月份9月-JDK16的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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