Home >Java >javaTutorial >How Do I Convert a java.util.Date to a String in Java?

How Do I Convert a java.util.Date to a String in Java?

DDD
DDDOriginal
2024-12-27 04:01:13464browse

How Do I Convert a java.util.Date to a String in Java?

How to Convert java.util.Date to String in Java

Java provides multiple ways to convert a java.util.Date object to a String representation. Here's one approach using the DateFormat#format method:

Convert a Date to a String with DateFormat#format

The following code snippet demonstrates how to convert a Date object to a String using the DateFormat#format method:

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

public class DateToStringExample {

    public static void main(String[] args) {
        String pattern = "MM/dd/yyyy HH:mm:ss";

        // Create an instance of SimpleDateFormat used for formatting 
        // the string representation of date according to the chosen pattern
        DateFormat df = new SimpleDateFormat(pattern);

        // Get the today date using Calendar object.
        Date today = Calendar.getInstance().getTime();        
        // Using DateFormat format method we can create a string 
        // representation of a date with the defined format.
        String todayAsString = df.format(today);

        // Print the result!
        System.out.println("Today is: " + todayAsString);
    }
}

This code will output the current date and time in the specified pattern.

The above is the detailed content of How Do I Convert a java.util.Date to a String in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn