How to convert a Java string to a time format?

In Java, you can utilize the `java.text.SimpleDateFormat` class to convert a string to a date format. Below is an example code:

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

public class Main {

    public static void main(String[] args) {

        String dateString = "2022-01-01 10:30:00";

        String pattern = "yyyy-MM-dd HH:mm:ss";

        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);

        try {

            Date date = dateFormat.parse(dateString);

            System.out.println(date);

        } catch (ParseException e) {

            e.printStackTrace();

        }

    }

}

In the code above, we start by defining a string `dateString` to represent the time string to be converted. Next, we define a pattern for the time format, using `”yyyy-MM-dd HH:mm:ss”` to denote year-month-day hour:minute:second. Then, we create a `SimpleDateFormat` object `dateFormat` and pass the pattern to its constructor. Afterwards, we use the `dateFormat.parse(dateString)` method to convert the string to a `Date` object and print the result. It is important to note that when using the `SimpleDateFormat` class for time format conversion, the format of the time string passed in must match the pattern, or else a `ParseException` will be thrown.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds