This article is shared from the Huawei Cloud Community " From Beginner to Mastery: Advanced Usage of SimpleDateFormat Class to Make Your Code Simpler!" ", author: bug bacteria.
Environment description: Windows 10 + IntelliJ IDEA 2021.3.2 + Jdk 1.8
@[toc]
Preface
Date and time are very common requirements in development, especially when dealing with time-related business logic, we need to format, compare and other operations on date and time. In Java, we can use SimpleDateFormat
classes to conveniently perform date and time formatting and parsing operations.
This article will introduce SimpleDateFormat
the advanced usage of the class, aiming to allow readers to better grasp the usage of this class and make the code more concise.
Summary
In this article, we will introduce the following aspects:
SimpleDateFormat
Overview and common uses of classesSimpleDateFormat
Class advanced usage- Code implementation and test cases
- Summary and Conclusion
SimpleDateFormat class
Overview
SimpleDateFormat
Class is a class in Java used for formatting and parsing date times. It provides a series of construction methods and format strings, allowing us to easily format and parse date and time.
Advantages and Disadvantages
SimpleDateFormat
It is a class used to format dates and times in Java. It inherits from the DateFormat class and is a thread-unsafe class.
advantage:
- Simple and easy to use, you can quickly format dates into specified formats and convert strings into corresponding date objects.
- The date format can be customized and multiple predefined formats are supported.
- Can be used for date parsing and formatting operations.
shortcoming:
SimpleDateFormat
It is not thread-safe and is not suitable for use in multi-threaded environments.- For some date formats, such as year, month, day, hour, minute, second and millisecond, it is necessary to use some specific characters to represent them, and these characters have a certain degree of difficulty and complexity.
Application scenarios
SimpleDateFormat
Suitable for date formatting and parsing scenarios, such as logging, database operations, e-commerce and other fields. For example, you can convert a timestamp into a date string in a specified format, or parse a date string into a corresponding date object. But be aware that since SimpleDateFormat
it is thread-unsafe, you need to synchronize it when using it in a multi-threaded environment, or use a thread-safe alternative such as the one Joda-Time
in the library DateTimeFormatter
.
Source code analysis
SimpleDateFormat
It is a classic time formatting class in Java. It can convert time into a string in a specified format, and it can also convert a string into a time in a specified format.
Among them SimpleDateFormat
, the class source code is more complicated because it involves a lot of time formatting rules. Here, we only briefly analyze its implementation principle.
1.Constructor
SimpleDateFormat
Classes have multiple constructors, of which the following two are more commonly used:
public SimpleDateFormat(String pattern) public SimpleDateFormat(String pattern, Locale locale)
The parameter of the first constructor is the time formatting template, that is, the format of the time string. The second constructor can specify geographic location information.
2. Format time
SimpleDateFormat
The main method of the class to format time into a string is format(). This method receives a Date type parameter and returns a formatted time string.
3. Parsing time
SimpleDateFormat
The main method of the class to parse a string into a time is that parse()
this method receives a time string as a parameter and returns a date object of type Date.
4. Thread safety
SimpleDateFormat
The class is not thread-safe because its internal state can be modified by multiple threads simultaneously. If you want to use it in a multi-threaded environment, you can use ThreadLocal
to achieve thread isolation.
In general, SimpleDateFormat
the class is a very commonly used time formatting class in Java, which can easily convert time into a string in a specified format, and can also parse a string into time. When using it, you should pay attention to its thread safety.
Common usage
Here are SimpleDateFormat
a few common uses of classes:
1. Format date and time
The methods of the SimpleDateFormat class format()
can format date and time according to the specified format. For example:
package com.demo.javase.day53; import java.text.SimpleDateFormat; import java.util.Date; /** * @author bug菌 * @date 2023/10/17 19:17 */ public class SimpleDateFormatTest { //格式化日期时间 public static void testFormat(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateStr = sdf.format(new Date()); System.out.println(dateStr); } public static void main(String[] args) { testFormat(); } }
The above code formats the current time into the format of "yyyy-MM-dd HH:mm:ss" and outputs it.
The output is as follows:
2023-10-17 19:21:45
The execution result screenshot is as follows:
2. Parse date and time
SimpleDateFormat
The methods of the class parse()
can parse strings in a specific format into Date objects. For example:
//解析日期时间 public static void testParse() throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse("2023-10-17"); System.out.println(date); } public static void main(String[] args) throws ParseException { testParse(); }
The above code parses the string "2021-08-01" into a Date object and outputs it. The output is as follows:
Tue Oct 17 00:00:00 CST 2023
The execution result screenshot is as follows:
3. Set time zone
Methods of the SimpleDateFormat class setTimeZone()
can set the time zone. For example:
//设置区时 public static void testSetTimeZone(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("GMT+8")); String dateStr = sdf.format(new Date()); System.out.println(dateStr); } public static void main(String[] args) throws ParseException { testSetTimeZone(); }
The above code sets the time zone GMT+8
and formats the current time into the format of "yyyy-MM-dd HH:mm:ss" for output. The output is as follows:
2023-10-17 19:25:43
The execution result screenshot is as follows:
Advanced usage
In addition to the above common usages, SimpleDateFormat
the class also has some advanced usages that allow us to format and parse date and time more flexibly.
1. Escape characters
SimpleDateFormat
Class supports the use of escape characters to output special characters. For example:
//转义字符 public static void testSimpleDateFormat(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss"); String dateStr = sdf.format(new Date()); System.out.println(dateStr); } public static void main(String[] args) throws ParseException { testSimpleDateFormat(); }
The above code uses single quotes to enclose "at" to indicate the output character "at". The output is as follows:
2023-10-17 at 19:27:24
The execution result screenshot is as follows:
2. Number formatting
SimpleDateFormat
The class supports using "#" and "0" for number formatting. Among them, "#" indicates optional digits, and "0" indicates that the missing digits are filled with 0s. For example:
//数字格式化 public static void testSimpleDateFormat_1(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); String dateStr = sdf.format(new Date()); System.out.println(dateStr); } public static void main(String[] args) throws ParseException { testSimpleDateFormat_1(); }
The above code formats the current time into the format of "yyyy-MM-dd HH:mm:ss.SSS" and outputs it. The output is as follows:
2023-10-17 19:28:31.478
The execution result screenshot is as follows:
3. Format mode
SimpleDateFormat
Class supports the use of formatting patterns to output date and time. The formatting pattern consists of date and time, which can be combined freely. Date formatting modes include "y", "M", "d", "E", etc., which respectively represent the year, month, day, day of the week, etc. Time formatting modes include "H", "m", "s", "S", etc., which respectively represent hours, minutes, seconds, milliseconds, etc. For example:
//格式化模式 public static void testSimpleDateFormat_2() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd E HH:mm:ss"); String dateStr = sdf.format(new Date()); System.out.println(dateStr); } public static void main(String[] args) throws ParseException { testSimpleDateFormat_2(); }
The above code formats the current time into the format of "yyyy-MM-dd E HH:mm:ss" and outputs it. The output is as follows:
2023-10-17 Tuesday 19:29:42
The execution result screenshot is as follows:
test case
code example
The following is SimpleDateFormat
sample code and test cases for using the class:
package com.demo.javase.day53; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /** * @author bugbug * @date 2023/10/17 19:17 * / public class SimpleDateFormatDemo { public static void main(String[] args) throws Exception { // Format date and time SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateStr1 = sdf1.format (new Date()); System.out.println(dateStr1); // Parse date and time SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd"); Date date2 = sdf2.parse("2023-10-17" ); System.out.println(date2); // Set time zone SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf3.setTimeZone(TimeZone.getTimeZone("GMT+8")) ; String dateStr3 = sdf3.format(new Date()); System.out.println(dateStr3); // Escape characters SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss") ; String dateStr4 = sdf4.format(new Date()); System.out.println(dateStr4); // Number formatting SimpleDateFormat sdf5 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); String dateStr5 = sdf5.format(new Date()); System.out.println(dateStr5); // Format mode SimpleDateFormat sdf6 = new SimpleDateFormat("yyyy-MM-dd E HH:mm:ss"); String dateStr6 = sdf6.format(new Date()); System.out.println(dateStr6); } }
Code analysis
For the above test case code, I will show you how to use SimpleDateFormat
classes in Java to format and parse dates. The details are as follows:
Format date time
SimpleDateFormat
The method used format()
is to format the current time and output the time in the specified format.
Parse date time
Use the SimpleDateFormat parse()
method to convert a string into a date of type Date.
Set time zone
Use the SimpleDateFormat setTimeZone()
method to set the time zone and change the default time zone to GMT+8.
escape character
Use single quotes and double quotes to enclose characters, indicating that this part of the content does not need to be formatted.
Number formatting
Add milliseconds to the formatted date.
Format mode
Use SimpleDateFormat
the defined formatting mode to output the date, day of week, and time in the specified format.
Overall, SimpleDateFormat
it's great for handling conversions of regular date formats and simple date calculations. But it should be noted that it is not thread-safe. If it is used in a multi-threaded environment, it needs to be synchronized or used to ThreadLocal
implement thread-local variables.
test execution
The output is as follows:
2023-10-17 19:31:16
Tue Oct 17 00:00:00 CST 2023
2023-10-17 19:31:16
2023-10-17 at 19:31:16
2023/10/17 19:31: 16.783
2023-10-17 Tuesday 19:31:16\
The execution result screenshot is as follows:
summary
This article introduces readers to SimpleDateFormat
the overview and common usage of classes, as well as some advanced usage. By studying this article, readers can better master SimpleDateFormat
the usage of classes and make the code more concise.
Appendix source code
All the source codes mentioned above have been uploaded and synchronized in "Gitee" , providing students with one-on-one reference learning to help you master it more quickly.
Summarize
In general, this article introduces SimpleDateFormat
an overview, common usage and advanced usage of commonly used date formatting and parsing classes in Java, as well as test cases and code implementations using this class. Among them, common usage includes formatting date and time, parsing date and time, and setting time zone, while advanced usage includes escaping characters, number formatting, and formatting modes.
In addition, this article also mentions SimpleDateFormat
the advantages, disadvantages and application scenarios. It should be noted that since SimpleDateFormat
it is a thread-unsafe class, it needs to be synchronized in a multi-threaded environment, or use a thread-safe alternative. By studying this article, readers can better master SimpleDateFormat
the usage of classes, and then handle date and time more flexibly.
Click to follow and learn about Huawei Cloud’s new technologies as soon as possible~
Lei Jun: The official version of Xiaomi’s new operating system ThePaper OS has been packaged. A pop-up window on the Gome App lottery page insults its founder. The U.S. government restricts the export of NVIDIA H800 GPU to China. The Xiaomi ThePaper OS interface is exposed. A master used Scratch to rub the RISC-V simulator and it ran successfully. Linux kernel RustDesk remote desktop 1.2.3 released, enhanced Wayland support After unplugging the Logitech USB receiver, the Linux kernel crashed DHH sharp review of "packaging tools": the front end does not need to be built at all (No Build) JetBrains launches Writerside to create technical documentation Tools for Node.js 21 officially released