📌  相关文章
📜  Java SimpleDateFormat(1)

📅  最后修改于: 2023-12-03 14:42:16.115000             🧑  作者: Mango

Java SimpleDateFormat

Java SimpleDateFormat is a class in Java's built-in java.text package that allows you to format and parse dates and times according to a specified pattern. It enables you to convert between the textual representation of dates and times and their actual values as Date objects.

Syntax

The syntax of a SimpleDateFormat pattern consists of various characters that represent different components of a date and time. These characters are combined together to form a pattern string, which is then passed as a parameter to the SimpleDateFormat constructor.

Some of the most commonly used characters are:

| Character | Description | | --- | --- | | y | Year | | M | Month | | d | Day of month | | h | Hour in AM/PM (1-12) | | H | Hour in day (0-23) | | m | Minute | | s | Second | | S | Millisecond | | E | Day name of the week | | a | AM/PM |

For example, the pattern string "yyyy-MM-dd" represents a date in the format of year-month-day, while "EEE, MMM d, ''yy" represents a date in the format of day of the week, month, day, and year with a two-digit year.

Usage

Here is an example use of the SimpleDateFormat class:

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

public class DateFormatExample {
    public static void main(String[] args) {
        Date currentDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");

        String formattedDate = dateFormat.format(currentDate);
        System.out.println(formattedDate);
    }
}

In this example, we create a Date object representing the current date and time, and then create a SimpleDateFormat object with the pattern string "dd/MM/yyyy HH:mm:ss". We then call the format() method of the SimpleDateFormat object to convert the Date object into a formatted String.

The output of this example would be something like "23/09/2021 12:34:56", depending on the current date and time.

Conclusion

In conclusion, SimpleDateFormat is a powerful tool for formatting and parsing dates and times in Java. By using a combination of different characters in a pattern string, you can create custom formats that suit your needs.