Home >Java >javaTutorial >How to Parse the Output of Java\'s Date#toString() Method?
Parsing Output of Date#toString() in Java
When working with dates in Java, you may encounter a need to parse the output of toString() method on a Date object. This method returns a string representation of the date, which can vary depending on the system locale. However, in this case, the output is "Sun Dec 12 13:45:12 CET 2010", suggesting that it's locale-independent.
Solving the Parsing Issue
To reliably parse this specific output, we can utilize SimpleDateFormat with a pattern that matches the format specified in Date#toString(). The pattern is as follows:
<code class="plaintext">EEE MMM dd HH:mm:ss zzz yyyy</code>
Code Example
Here's a code example demonstrating how to use SimpleDateFormat to parse the output of Date#toString():
<code class="java">import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateToStringParser { public static void main(String[] args) throws ParseException { String dateString = "Sun Dec 12 13:45:12 CET 2010"; SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); Date date = dateFormat.parse(dateString); System.out.println("Parsed Date: " + date); } }</code>
Note
While this solution solves the parsing issue, it's generally considered better practice to use SimpleDateFormat#format() instead of Date#toString() to ensure consistent date formatting.
The above is the detailed content of How to Parse the Output of Java\'s Date#toString() Method?. For more information, please follow other related articles on the PHP Chinese website!