Home  >  Article  >  Java  >  How to Reliably Parse the Output of `Date.toString()` in Java?

How to Reliably Parse the Output of `Date.toString()` in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 19:32:30703browse

How to Reliably Parse the Output of `Date.toString()` in Java?

How to Reliably Parse the Output of Date.toString()

When attempting to parse the output of new Date().toString(), developers often encounter challenges due to the lack of locale-specific formatting. This can lead to inconsistent and unreliable results.

To resolve this issue, the solution lies in understanding the underlying format specified in the Date#toString() documentation. The format is as follows:

dow mon dd hh:mm:ss zzz yyyy

Where:

  • dow is the day of the week in abbreviated form (e.g., Sun)
  • mon is the month in abbreviated form (e.g., Dec)
  • dd is the day of the month (e.g., 12)
  • hh is the hour (0-23) (e.g., 13)
  • mm is the minute (0-59) (e.g., 45)
  • ss is the second (0-59) (e.g., 12)
  • zzz is the time zone name or abbreviation (e.g., CET)
  • yyyy is the year (e.g., 2010)

Translating this into a SimpleDateFormat pattern, we get:

EEE MMM dd HH:mm:ss zzz yyyy

For example, the German-formatted string "Sun Dec 12 13:45:12 CET 2010" can be parsed using the following SimpleDateFormat:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

By using this pattern, you can reliably parse the output of Date#toString() and convert it into a Date object, regardless of the system locale settings.

The above is the detailed content of How to Reliably Parse the Output of `Date.toString()` 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