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

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

DDD
Release: 2024-12-08 03:05:12
Original
632 people have browsed it

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

Converting java.util.Date to String

In Java, the java.util.Date class represents a specific instant in time. However, if you need to work with the date as a string, you'll need to convert it to a string format.

Solution

To convert a Date object to a string, you can use the DateFormat#format method. This method allows you to specify a formatting pattern that determines how the date will be converted.

Here's an example of how you can use the DateFormat#format method:

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);
Copy after login

In this example, the pattern variable specifies the format of the output string. The df variable is an instance of SimpleDateFormat that is used to format the date. The today variable is an instance of Date that represents the current date and time. The todayAsString variable is a string representation of the current date and time.

You can find more examples of how to use the DateFormat#format method at http://www.kodejava.org/examples/86.html.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template