How to realize the time formatting of learning Java63 from scratch?

foreword

In the last article, I explained to you in Java Date和Calendar类, you should have learned how to create a time and date object, and use this object to perform some operations on time.

But in the previous article, we know that the time format of the time object constructed by default is not suitable for us to read. And during development, the time formats displayed on PC, Android, and iOS may not be exactly the same, so is there any way for us to customize the time format?

Of course, this demand can be realized, which requires the use of what we are going to learn today, which is the formatting of time!


The full text is about [3200] words, no nonsense, just pure dry goods that allow you to learn techniques and understand principles! This article has a wealth of cases and pictures, so that you can better understand and use the technical concepts in the article, and can bring you enough enlightening thinking...

1. Time pattern string

Before formatting the time, let's take a look at the time pattern string.

The so-called time pattern string is a pattern that can be used to specify the time format. In this pattern, some ASCII letters are reserved as pattern letters with special meanings, as shown in the following table:

letter describe example
y four digit year 2020
M month July or 07
d day of the month 10
h Hour in AM/PM (1~12) format 12
H Hour of the day (0~23) 22
m minutes 30
s The number of seconds 55
S milliseconds 234
E Day of the week Tuesday
D days of the year 360
F The day of the week of the week of the month 2 (second Wed. in July)
w week of the year 40
W week of the month 1
a AM (morning)/PM (afternoon) PM
k Hour of the day (1~24) 24
K Hour in AM/PM (0~11) format 10
z Time zone Eastern Standard Time
text delimiter Delimiter

We try to remember the symbols in the above table, because these symbols are often used in development. After mastering these symbols, we can continue to learn the formatting skills of date and time.

2. printf() formatting method

If we just want to simply format the date and time in a certain part of the project, we can actually use the printf() method. When the printf() method formats the time and date, it needs to use two letters for formatting operations, usually starting with %t and ending with a letter in the following table.

conversion character illustrate example
c Include full date and time information Sat Oct 27 14:21:20 CST 2007
F "Year-Month-Day" format 2007-10-27
D "Month/Day/Year" format 10/27/07
r "HH:MM:SS PM" format (12-hour format) 02:25:51 PM
T "HH:MM:SS" format (24 hour format) 14:28:16
R "HH:MM" format (24 hour format) 14:28

Next, let's use a case to see how the printf() method formats the time.

import java.util.Date;

public class Demo07 {
    
    

	public static void main(String[] args) {
    
    
		// 初始化 Date 对象
		Date date = new Date();
		//c:全部日期和时间
		System.out.printf("全部日期和时间信息:%tc%n", date);
		//f:年-月-日
		System.out.printf("年-月-日的格式:%tF%n", date);
		//d:月/日/年
		System.out.printf("月/日/年的格式:%tD%n", date);
		//r:HH:MM:SS PM
		System.out.printf("HH:MM:SS PM的格式(12时制):%tr%n", date);
		//t:HH:MM:SS格式(24时制)
		System.out.printf("HH:MM:SS的格式(24时制):%tT%n", date);
		//R:HH:MM格式(24时制)
		System.out.printf("HH:MM的格式(24时制):%tR", date);

        //用格式化字符串,指出要被格式化的参数索引,索引必须紧跟在%后面,而且必须以$结束
		//使用toString()显示日期和时间
	    System.out.printf("%1$s %2$tB %2$td, %2$tY","Due date:", date);
	}
}

When the printf() method is formatted, several symbols in the above table need to be combined. But to be honest, this formatting method is not very commonly used, and it is mainly suitable for a small number of individual places. If there are many places in our project that need to be formatted, try not to use this method. Because if you need to provide the date repeatedly, using this method to format the time is a bit complicated, and it is not easy to maintain later.

3. DateFormat class

In fact, we format the date in the Java project, mainly by using some date formatting classes, such as DateFormatits subclasses.

1 Introduction

DateFormatis an abstract class responsible for date/time formatting, which can format and parse a date or time in a language-independent manner. Its subclasses (such as SimpleDateFormat) allow date formatting, converting dates to text; they can also parse text, converting text to dates.

We cannot use the new keyword when creating a DateFormat object, but use the getDateInstance() static method in the DateFormat class, as shown below:

DateFormat df = DateFormat.getDatelnstance();

2. Static constants

DateFormat provides us with several commonly used static constants to facilitate our formatting style settings, as follows:

● SHORT: pure numbers, such as 12.5.10 or 5:30pm;

● MEDIUM: longer, such as May 10, 2023;

● LONG: longer, such as May 12, 2023 or 11:15:32am;

● FULL: Fully specified, such as Tuesday, May 10, 2022 AD, or 11:l5:42am CST.

3. Common methods

After we create a DateFormat object, we can use the methods in the object to format the date/time. The common methods in DateFormat are shown in the following table:

method describe
String format(Date date) Format Date as a date/time string
Calendar getCalendar() Get the calendar associated with this date/time format
static DateFormat getDateInstance() Get the date format with default formatting style and default locale
static DateFormat getDateInstance(int style) Get the date format with the specified formatting style and default locale
static DateFormat getDateInstance(int style,Locale locale) Get the date format with the specified formatting style and the specified locale
static DateFormat getDateTimeInstance() Get the date/time format with default formatting style and default locale
static DateFormat getDateTimeInstance(intdateStyle,int timeStyle) Gets a date/time format with the specified date/time formatting style and default locale
static DateFormat getDateTimeInstance(intdateStyle,int timeStyle,Locale locale) 获取具有指定日期/时间格式化风格和指定语言环境的日期/时间格式
static DateFormat getTimeInstance() 获取具有默认格式化风格和默认语言环境的时间格式
static DateFormat getTimeInstance(int style) 获取具有指定格式化风格和默认语言环境的时间格式
static DateFormat getTimeInstance(int style,Locale locale) 获取具有指定格式化风格和指定语言环境的时间格式
void setCalendar(Calendar newCalendar) 为此格式设置日历
Date parse(String source) 将给定的字符串解析成日期/时间

4. 基本使用

接下来我们通过一个案例来看看DateFormat的用法。这个案例,主要是给大家介绍DateFormat类的方法与静态常量该如何使用,对日期进行不同风格的格式化。
在这里插入图片描述

四. SimpleDateFormat类

1. 简介

虽然我们已经有了DateFormat,但有时候这个类并不能满足我们的实际开发需求。此时我们可以进一步使用它的子类,比如SimpleDateFormat来进行更多的操作。

SimpleDateFormat是一个以与语言环境有关的方式来格式化和解析日期的具体类,它具有格式化(日期转文本)、解析(文本转日期)和规范化的功能。相对DateFormat来说,SimpleDateFormat具有更高的灵活性,可以让我们选择任何自定义的日期/时间格式,进行个性化设置。

2. 构造方法

SimpleDateFormat是一个具体的子类,所以我们是可以通过new的方式来创建对象的。SimpleDateFormat类为我们提供了如下4个构造方法:

● SimpleDateFormat():用默认的格式和语言环境,构造一个SimpleDateFormat对象;

● SimpleDateFormat(String pattern):用指定的格式和默认的语言环境,构造一个SimpleDateF ormat对象;

● SimpleDateFormat(String pattern,Locale locale):用指定的格式和指定的语言环境,构造一个 SimpleDateFormat对象;

● SimpleDateFormat(String pattern,DateFormatSymbols formatSymbols):用指定的格式和指定的格式化语法来构造一个SimpleDateFormat对象。

3. 自定义格式化常用字母

SimpleDateFormat自定义格式中常用的字母及含义如表 2 所示。

字母 含义 示例
y 年份。一般用 yy 表示两位年份,yyyy 表示 4 位年份 使用 yy 表示的年扮,如 11;使用 yyyy 表示的年份,如 2011
M 月份。一般用 MM 表示月份,如果使用 MMM,则会根据语言环境显示不同语言的月份 使用 MM 表示的月份,如 05;使用 MMM 表示月份,在 Locale.CHINA语言环境下,如“十月”;在 Locale.US语言环境下,如 Oct
d 月份中的天数。一般用 dd 表示天数 使用 dd 表示的天数,如 10
D 年份中的天数。表示当天是当年的第几天, 用 D 表示 使用 D 表示的年份中的天数,如 295
E 星期几。用 E 表示,会根据语言环境的不同, 显示不同语言的星期几 使用 E 表示星期几,在 Locale.CHINA 语言环境下,如“星期四”;在 Locale.US 语言环境下,如 Thu
H 一天中的小时数(0~23)。一般用 HH 表示小时数 使用 HH 表示的小时数,如 18
h 一天中的小时数(1~12)。一般使用 hh 表示小时数 使用 hh 表示的小时数,如 10 (注意 10 有可能是 10 点,也可能是 22 点)
m 分钟数。一般使用 mm 表示分钟数 使用 mm 表示的分钟数,如 29
s 秒数。一般使用 ss 表示秒数 使用 ss 表示的秒数,如 38
S 毫秒数。一般使用 SSS 表示毫秒数 使用 SSS 表示的毫秒数,如 156

4. 基本使用

接下来我们通过一个案例,来展示SimpleDateFormat的格式化和解析用法。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo09 {
    
    

	public static void main(String[] args) {
    
    
		//设置日期时间格式化模式,这个模式是根据需求自定义展示的,也可以是"yyyy年MM月dd日 E HH点 mm分 ss秒"等格式
		SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//进行日期格式化
		String date = format.format(new Date());
		System.out.println("格式后的结果:" + date);
		
		try {
    
    
			//解析日期,将一个时间字符串解析为Date类型,这里有可能会产生解析异常
			String time="2022-02-12 17:30:39";
			Date date2 = format.parse(time);
			System.out.println("解析后的结果:" + date2);
		} catch (ParseException e) {
    
    
			e.printStackTrace();
		}
	}
}

在上述案例中,format()方法用于将Date格式化为String字符串,parse()方法用于将String字符串解析为Date类型。其中yyyy是完整的公元年,MM是月份,dd是日期,HH:mm:ss 是时、分、秒。这里有的格式大写,有的格式小写,例如MM是月份,mm是分,HH是24小时制,而hh则是12小时制。


五. 结语

至此我们就把日期的格式化操作给大家讲解完毕了。今天的内容其实并不难,大家只需要把一些常用的构造方式及方法、常量记一下即可。

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/130598945