Home > Java > javaTutorial > How to Format a java.util.Date Object as a String in Java?

How to Format a java.util.Date Object as a String in Java?

Barbara Streisand
Release: 2024-12-13 14:47:11
Original
515 people have browsed it

How to Format a java.util.Date Object as a String in Java?

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

Problem:

You need to convert a java.util.Date object to a formatted String in Java, specifically in the format "2010-05-30 22:15:52".

Solution:

To convert a java.util.Date to a String in Java, you can use the DateFormat.format() method. This method takes a Date object and a formatting pattern as input and returns a formatted String.

Here's an example:

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

This code will print the current date and time in the specified format:

Today is: 05/30/2010 22:15:52
Copy after login

Source:

http://www.kodejava.org/examples/86.html

The above is the detailed content of How to Format a java.util.Date Object as 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template