SoFunction
Updated on 2025-03-04

A detailed explanation of Java time format conversion

Preface

In Java development, processing of time and dates is a very common requirement. Whether it is the time data entered by the user or the time stamp generated by the system, we often need to format or parse it. This article will introduce in detail how to convert time formats in Java, and introduce two main methods:SimpleDateFormat(Applicable to Java 8) and(Applicable to Java 8 and later).

1. Before Java 8: SimpleDateFormat

1. What is SimpleDateFormat

SimpleDateFormatIt is a very important class in Java, which allows you toDateFormat the object as a string, or parse the string asDateObject. It provides a rich date and time format pattern to help you convert according to different needs.

2. Commonly used date and time patterns

existSimpleDateFormatIn  , use a specific pattern string to define the format of date and time. Commonly used pattern symbols are as follows:

  • yyyy: The year of four digits, such as2024
  • MM: The month for two people, such as01(January)
  • dd: The date of two digits, such as15(15th)
  • HH: 24-hour hours, such as13(1 pm)
  • mm: Two minutes, such as45(45 minutes)
  • ss: Two digits of seconds, such as30(30 seconds)
  • a:AM/PM tags

3. Format and parse examples

Format date

You can useSimpleDateFormatFormat the current time into a custom string format:

import ;
import ;

public class DateFormatExample {
    public static void main(String[] args) {
        // Get the current time        Date now = new Date();
        
        // Define date format        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        // Format the current time        String formattedDate = (now);
        ("Formatted Date: " + formattedDate);
    }
}

Output:

Formatted Date: 2024-10-15 13:45:30

Parsing the string as a date

Similarly, you can useSimpleDateFormatParses the string into a date object:

import ;
import ;

public class DateParseExample {
    public static void main(String[] args) {
        String dateStr = "2024-10-15 13:45:00";
        
        // Define date format        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        try {
            // Parses the string into a date object            Date parsedDate = (dateStr);
            ("Parsed Date: " + parsedDate);
        } catch (Exception e) {
            ();
        }
    }
}

Output:

Parsed Date: Tue Oct 15 13:45:00 CST 2024

4. Things to note

  • Thread safety issuesSimpleDateFormatIt is not thread-safe. If multiple threads use the same one at the same timeSimpleDateFormatInstances, may produce unpredictable behavior. Therefore, in a multi-threaded environment, it is recommended to create its own for each threadSimpleDateFormatExample, or useThreadLocalTo solve thread safety problems.

  • Exception handling: When parsing a string, if the format does not match,parseThe method will be thrownParseException. So make sure that the exception is handled in the code.

2. Java 8 and after: Package

Java 8 introduces a new date-time API, providing more modern and easy-to-use date processing capabilities, replacing the old onesDateandSimpleDateFormat. The new API provides more functionality, safer threading, and more in line with human logic.

1. Core category introduction

These classes provide powerful time processing capabilities, and they are both immutable and thread-safe.

2. Format date and time using DateTimeFormatter

DateTimeFormatterClasses are used to format date and time objects as strings, and can parse strings into date and time objects. It provides a comparisonSimpleDateFormatMore flexible and rich format definitions.

Example of formatting date and time

The following code shows how to use itDateTimeFormatterFormatLocalDateTime

import ;
import ;

public class DateTimeFormatExample {
    public static void main(String[] args) {
        // Get the current date and time        LocalDateTime now = ();
        
        // Define the formatting mode        DateTimeFormatter formatter = ("yyyy-MM-dd HH:mm:ss");
        
        // Format date and time        String formattedDateTime = (formatter);
        ("Formatted DateTime: " + formattedDateTime);
    }
}

Output:

Formatted DateTime: 2024-10-15 13:45:30

3. Parsing the string as date and time

Similar to formatting, you can useDateTimeFormatterParse the string toLocalDateTimeObject. The following example shows how to parse:

import ;
import ;

public class DateTimeParseExample {
    public static void main(String[] args) {
        String dateTimeStr = "2024-10-15 13:45:00";
        
        // Define the parsing mode        DateTimeFormatter formatter = ("yyyy-MM-dd HH:mm:ss");
        
        // parse the string as a LocalDateTime object        LocalDateTime parsedDateTime = (dateTimeStr, formatter);
        ("Parsed DateTime: " + parsedDateTime);
    }
}

Output:

Parsed DateTime: 2024-10-15T13:45

4. Common formatting modes

  • yyyy- Year, four digits, for example: 2023

  • MM- Month, double digits, for example: 01

  • dd- Date, double digits, for example: 08

  • HH- Hours (24-hour system), double digits, for example: 20

  • mm- Minutes, double digits, for example: 30

  • ss- Seconds, double digits, for example: 59

  • SSS- milliseconds, three digits

5. The use of LocalDate and LocalTime

LocalDateandLocalTimeClasses are used to deal with scenarios with only dates and only time, respectively. They can also be usedDateTimeFormatterTo format and parse.

Format LocalDate

import ;
import ;

public class LocalDateFormatExample {
    public static void main(String[] args) {
        LocalDate today = ();
        
        DateTimeFormatter formatter = ("yyyy/MM/dd");
        
        String formattedDate = (formatter);
        ("Formatted LocalDate: " + formattedDate);
    }
}

Output:

Formatted LocalDate: 2024/10/15

Analysis LocalDate

import ;
import ;

public class LocalDateParseExample {
    public static void main(String[] args) {
        String dateStr = "2024/10/15";
        
        DateTimeFormatter formatter = ("yyyy/MM/dd");
        
        LocalDate parsedDate = (dateStr, formatter);
        ("Parsed LocalDate: " + parsedDate);
    }
}

Output:

Parsed LocalDate: 2024-10-15

6. Operation of date and time

In addition to formatting and parsing, the date and time API of Java 8 also provides rich operational functions, such as date addition and subtraction, calculating time difference, etc.

Date addition and subtraction operations

import ;

public class DateManipulationExample {
    public static void main(String[] args) {
        LocalDate today = ();
        
        LocalDate nextWeek = (1);
        ("One week later: " + nextWeek);
        
        LocalDate previousMonth = (1);
        ("One month ago: " + previousMonth);
    }
}

Output:

One week later: 2024-10-22
One month ago: 2024-09-15

Calculate the time difference

import ;
import ;

public class DateDifferenceExample {
    public static void main(String[] args) {
        LocalDate startDate = (2024, 10, 1);
        LocalDate endDate = (2024, 12, 31);
        
        Period period = (startDate, endDate);
        
        ("Months between: " + ());
        ("Days between: " + ());
    }
}

Output:

Months between: 2
Days between: 30

3. Summary

When converting time formats in Java, it is important to choose the right tool:

Through these classes and methods, you can easily complete the conversion, formatting, parsing and manipulation of time formats, thereby improving the readability and maintenance of your code.

I hope you like this blog post about Java time format conversion in detail! Please like and bookmark it. I wish all the handsome guys and beauties who like and collect it will get rich this year. If you have more questions, feel free to ask questions.

  • LocalDate: Represents a date and does not contain the time part, for example2024-10-15
  • LocalTime: represents a time, not containing the date part, for example13:45:30
  • LocalDateTime: Represents an object containing date and time, for example2024-10-15T13:45:30
  • DateTimeFormatter: used for formatting and parsingLocalDateLocalTimeandLocalDateTime
  • yyyy-MM-dd:For example2024-10-15, indicating year, month, day.
  • HH:mm:ss:For example13:45:30, indicating time, minute and second.
  • yyyy-MM-dd HH:mm:ss:For example2024-10-15 13:45:30, indicating the complete date and time.
  • dd/MM/yyyy:For example15/10/2024, a commonly used date format in Europe.
  • Before Java 8: Can be usedSimpleDateFormat, but pay attention to thread safety issues.
  • Java 8 and later: Recommended to use new onesPackage, it provides a more concise, intuitive, thread-safe date and time processing tool.

Summarize

This is the end of this article about Java time format conversion. For more related Java time format conversion content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!