Home >Java >javaTutorial >How to Parse Date Output from `Date.toString()` in Java?

How to Parse Date Output from `Date.toString()` in Java?

Susan Sarandon
Susan SarandonOriginal
2024-10-29 00:16:021058browse

How to Parse Date Output from `Date.toString()` in Java?

Parsing Date Output from Date.toString()

In Java, the toString() method of the Date class generates a date string in a specific format. This format varies depending on the locale of the user's system. However, sometimes it is necessary to parse this string regardless of localization settings.

This is where SimpleDateFormat comes into play. SimpleDateFormat allows for parsing and formatting dates in a specific pattern. To parse the output of new Date().toString(), we need to specify the corresponding pattern.

The toString() method generates a date string in the format:

EEE MMM dd HH:mm:ss zzz yyyy

Where:

  • EEE is the abbreviated weekday
  • MMM is the abbreviated month
  • dd is the day of the month (0-padded)
  • HH is the hour (0-padded)
  • mm is the minute (0-padded)
  • ss is the second (0-padded)
  • zzz is the time zone name
  • yyyy is the year

In SimpleDateFormat pattern terms, this translates to:

EEE MMM dd HH:mm:ss zzz yyyy

Therefore, to parse the output of new Date().toString(), we can use the following SimpleDateFormat pattern:

<code class="java">SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
Date date = sdf.parse(dateString);</code>

The above is the detailed content of How to Parse Date Output from `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