首页 > 其他分享 >DateFormat

DateFormat

时间:2023-12-20 15:57:04浏览次数:20  
标签:format Locale DateFormat Date time date

概述

{@code DateFormat} is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner.
The date/time formatting subclass, such as {@link SimpleDateFormat}, allows for formatting (i.e., date → text), parsing (text → date), and normalization.
The date is represented as a <code>Date</code> object or as the milliseconds since January 1, 1970, 00:00:00 GMT.

DateFormat 用于格式化Date/time & 解析text到Date;

DateFormat的子类SimpleDateFormat,允许将Date转换为text,解析text为Date

date表示 Date对象自1970 年 1 月 1 日 00:00:00 GMT 以来的毫秒数

 

{@code DateFormat} provides many class methods for obtaining default date/time formatters based on the default or a given locale and a number of formatting styles.
The formatting styles include {@link #FULL}, {@link #LONG}, {@link #MEDIUM}, and {@link #SHORT}.

DateFormat提供了许多格式化样式:FULL、LONG、MEDIUM、SHORT;

 

{@code DateFormat} helps you to format and parse dates for any locale.
Your code can be completely independent of the locale conventions for months, days of the week, or even the calendar format: lunar vs. solar.

DateFormat可以 格式化&解析  任何环境的 date

DateFormat 独立于 阴历/阳历 的月份、星期等

 

To format a date for the current Locale, use one of the static factory methods: String myString = DateFormat.getDateInstance().format(myDate);

可以使用static工厂方法 DateFormat.getDateInstance().format(myDate) 格式化当前区域的date;

  

To format a date for a different Locale, specify it in the call to {@link #getDateInstance(int, Locale) getDateInstance()}.
  eg:DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);

为不同的区域设置的date 格式化,需要在调用时指定getDateInstance(int, Locale);

Date date = new Date();
        String format2 = DateFormat.getDateInstance(DateFormat.FULL, Locale.CHINA).format(date);
        System.out.println(format2); // 2023年12月20日 星期三
        String format3 = DateFormat.getDateInstance(DateFormat.LONG, Locale.CHINA).format(date);
        System.out.println(format3); // 2023年12月20日
        String format4 = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.CHINA).format(date);
        System.out.println(format4); // 2023-12-20
        String format5 = DateFormat.getDateInstance(DateFormat.SHORT, Locale.CHINA).format(date);
        System.out.println(format5); // 23-12-20

  

You can use a DateFormat to parse also.

Date myDate = df.parse(myString);

Date parse = DateFormat.getDateTimeInstance().parse("2023-12-23 12:23:34");
        System.out.println(parse); // Sat Dec 23 12:23:34 CST 2023

  

 

Use {@code getDateInstance} to get the normal date format for that country.
There are other static factory methods available.
Use {@code getTimeInstance} to get the time format for that country.
Use {@code getDateTimeInstance} to get a date and time format.

getDateInstance 获取 当前地区的正常 date format

getTimeInstance 获取 time format

getDateTimeInstance 获取 date And time format

Date date1 = new Date();
        String format6 = DateFormat.getDateInstance().format(date1);
        System.out.println(format6); //2023-12-20
        String format7 = DateFormat.getTimeInstance().format(date1);
        System.out.println(format7); // 15:29:04
        String format8 = DateFormat.getDateTimeInstance().format(date1);
        System.out.println(format8); // 2023-12-20 15:29:04

 

You can pass in different options to these factory methods to control the length of the result; from {@link #SHORT} to {@link #MEDIUM} to {@link #LONG} to {@link #FULL}.
The exact result depends on the locale, but generally:
{@link #SHORT} is completely numeric, such as {@code 12.13.52} or {@code 3:30pm}
{@link #MEDIUM} is longer, such as {@code Jan 12, 1952}
{@link #LONG} is longer, such as {@code January 12, 1952} or {@code 3:30:32pm}
{@link #FULL} is pretty completely specified, such as {@code Tuesday, April 12, 1952 AD or 3:30:42pm PST}.

可以在 static factory methods的参数设置 格式样式:SHORT、MEDIUM、LONG、FULL;

 

You can also set the time zone on the format if you wish.
If you want even more control over the format or parsing, (or want to give your users more control), you can try casting the {@code DateFormat} you get from the factory methods to a {@link SimpleDateFormat}.
This will work for the majority of countries; just remember to put it in a {@code try} block in case you encounter an unusual one.

如果你想,还可以设置时区

可以使用SimpleDateFormat,建议放入try中,以防异常情况;

 

Date formats are not synchronized.
It is recommended to create separate format instances for each thread.
If multiple threads access a format concurrently, it must be synchronized externally.

DateFormat是线程非同步的;

 

public abstract class DateFormat extends Format {

        /**
         * Constant for full style pattern.
         */
        public static final int FULL = 0;
        /**
         * Constant for long style pattern.
         */
        public static final int LONG = 1;
        /**
         * Constant for medium style pattern.
         */
        public static final int MEDIUM = 2;
        /**
         * Constant for short style pattern.
         */
        public static final int SHORT = 3;
        /**
         * Constant for default style pattern.  Its value is MEDIUM.
         */
        public static final int DEFAULT = MEDIUM;

        public final static DateFormat getDateInstance()
        {
            return get(0, DEFAULT, 2, Locale.getDefault(Locale.Category.FORMAT));
        }

        public final static DateFormat getTimeInstance()
        {
            return get(DEFAULT, 0, 1, Locale.getDefault(Locale.Category.FORMAT));
        }

        public final static DateFormat getDateTimeInstance()
        {
            return get(DEFAULT, DEFAULT, 3, Locale.getDefault(Locale.Category.FORMAT));
        }

        /**
         * Creates a DateFormat with the given time and/or date style in the given locale.
         * @param timeStyle a value from 0 to 3 indicating the time format, ignored if flags is 2
         * @param dateStyle a value from 0 to 3 indicating the time format, ignored if flags is 1
         * @param flags either 1 for a time format, 2 for a date format, or 3 for a date/time format
         * @param loc the locale for the format
         */
        private static DateFormat get(int timeStyle, int dateStyle, int flags, Locale loc) {
            if ((flags & 1) != 0) {
                if (timeStyle < 0 || timeStyle > 3) {
                    throw new IllegalArgumentException("Illegal time style " + timeStyle);
                }
            } else {
                timeStyle = -1;
            }
            if ((flags & 2) != 0) {
                if (dateStyle < 0 || dateStyle > 3) {
                    throw new IllegalArgumentException("Illegal date style " + dateStyle);
                }
            } else {
                dateStyle = -1;
            }

            LocaleProviderAdapter adapter = LocaleProviderAdapter.getAdapter(DateFormatProvider.class, loc);
            DateFormat dateFormat = get(adapter, timeStyle, dateStyle, loc);
            if (dateFormat == null) {
                dateFormat = get(LocaleProviderAdapter.forJRE(), timeStyle, dateStyle, loc);
            }
            return dateFormat;
        }

        public final String format(Date date) {
            return format(date, new StringBuffer(), DontCareFieldPosition.INSTANCE).toString();
        }

        public Date parse(String source) throws ParseException
        {
            ParsePosition pos = new ParsePosition(0);
            Date result = parse(source, pos);
            if (pos.index == 0)
                throw new ParseException("Unparseable date: \"" + source + "\"" , pos.errorIndex);
            return result;
        }
    }

  

  

 

标签:format,Locale,DateFormat,Date,time,date
From: https://www.cnblogs.com/anpeiyong/p/17916661.html

相关文章

  • Java SimpleDateFormat的使用方法
    JavaSimpleDateFormat的使用方法使用Date直接输出日期时,是使用系统默认的格式输出,所以需要使用SimpleDateFormat来格式化日期。那么SimpleDateFormat类怎么使用呢,我们需要先了解此类的格式化符号y:代表年份M:代表月份d:代表月份中的那一天,也就是日H:代表小时m:代表分钟s:代表秒......
  • 07SimpleDateFormat类
    SimpleDateFormat类SimpleDateFormat类是一个以与语言环境有关的方式来格式化和解析日期的具体类。进行格式化(日期-->文本)、解析(文本-->日期)。常用的时间模式字母字母日期或时间示例y年2023M年中月份01d月中天份09H一天中的小时数(0-23......
  • 想让你的代码简洁,试试这个SimpleDateFormat类高深用法
    本文分享自华为云社区《从入门到精通:SimpleDateFormat类高深用法,让你的代码更简洁!》,作者:bug菌。环境说明:Windows10+IntelliJIDEA2021.3.2+Jdk1.8@[toc]前言日期时间在开发中是非常常见的需求,尤其是在处理与时间相关的业务逻辑时,我们需要对日期时间进行格式化、比较......
  • 关于 npoi 的 DateUtil.IsCellDateFormatted(cell) 为true,取cell.DateCellValue却报
    NPOI中数字和日期都是NUMERIC类型的,这里对其进行判断是否是日期类型所以当 DateUtil.IsCellDateFormatted为true时,理论是应该可以取到  cell.DateCellValue但实际上,cell.DateCellValue可能会报异常,而取 cell.NumericCellValue却是正常的,HSSFWorkbook是excel2007以前......
  • SimpleDateFormat线程安全性
    SimpleDateFormat线程安全性0结论SimpleDateFormat是线程不安全的。在JDK中关于SimpleDateFormat有这样一段描述:Dateformatsarenotsynchronized.Itisrecommendedtocreateseparateformatinstancesforeachthread.Ifmultiplethreadsaccessaformatconcurr......
  • SimpleDateFormat详解
    publicclassSimpleDateFormatextendsDateFormatSimpleDateFormat是一个以国别敏感的方式格式化和分析数据的具体类。它允许格式化(date->text)、语法分析(text->date)和标准化。SimpleDateFormat允许以为日期-时间格式化选择任何用户指定的方式启动。但是,希望用......
  • SimpleDateFormat 线程安全问题修复方案
    问题介绍在日常的开发过程中,我们不可避免地会使用到JDK8之前的Date类,在格式化日期或解析日期时就需要用到SimpleDateFormat类,但由于该类并不是线程安全的,所以我们常发现对该类的不恰当使用会导致日期解析异常,从而影响线上服务可用率。以下是对SimpleDateFormat类不恰当......
  • 【高并发】SimpleDateFormat类到底为啥不是线程安全的?(附六种解决方案,建议收藏)
    大家好,我是冰河~~首先问下大家:你使用的SimpleDateFormat类还安全吗?为什么说SimpleDateFormat类不是线程安全的?带着问题从本文中寻求答案。提起SimpleDateFormat类,想必做过Java开发的童鞋都不会感到陌生。没错,它就是Java中提供的日期时间的转化类。这里,为什么说SimpleDateFormat类有......
  • SimpleDateFormat线程安全问题探究
    目录一.问题现象二.原因排查三.原因分析四.解决方案一.问题现象运营部门反馈使用小程序配置的拉新现金红包活动二维码,在扫码后跳转至404页面。二.原因排查1、首先,检查扫码后的跳转链接地址不是对应二维码的实际URL,根据代码逻辑推测,可能是accessToken在微信端已失效导致,检查数......
  • 【高并发】SimpleDateFormat类到底为啥不是线程安全的?(附六种解决方案,建议收藏)
    大家好,我是冰河~~首先问下大家:你使用的SimpleDateFormat类还安全吗?为什么说SimpleDateFormat类不是线程安全的?带着问题从本文中寻求答案。提起SimpleDateFormat类,想必做过Java开发的童鞋都不会感到陌生。没错,它就是Java中提供的日期时间的转化类。这里,为什么说SimpleDateFormat......