This question already has an answer here:
- Change date format in a Java string 18 answers
- how to parse output of new Date().toString() 3 answers
I have a string "Mon Jan 01 00:00:00 AEDT 1990" and I need to convert it into the format "yyyyMMdd" so in this case it would be "19900101".
I think it's possible to do this with Regular Expressions so that I could pull out the year, month(but would need to convert Jan to 01 and etc) and day from the string but I am not well versed in Regular Expressions. Anyone have any ideas?
Check if something like this helps
Parse date with AEDT and AEST time zone in java
tl;dr
Regex is overkill.
Here is a one-liner solution using java.time classes built into Java.
java.time
Regex is overkill for this.
The modern approach uses java.time classes.
Specify a custom formatting pattern to fit your input.
Specify a locale to facilitate translating the name of day-of-week and name of month.
ZonedDateTime
Parse as a
ZonedDateTime
, a moment as seen through the wall-clock time used by the people of a specific region (a time zone).By the way, your input string is in a terrible format. It uses the 2-4 character pseudo-zones that are not actual time zones, not standardized, and are not unique! Another problem is depending on English. And it is difficult to parse. Educate the people publishing your data about the beauty of the ISO 8601 standard, created for exchanging date-time values as text.
LocalDate
You want only the date. So extract a
LocalDate
.Your desired output format has already been defined in the
DateTimeFormatter
class. The standard ISO 8601 format for a date is YYYY-MM-DD. A variation of that is known as "Basic" meaning it minimizes the use of delimiters: YYYYMMDD.Now assuming that each month and day names inside each passed string is matching one of enum
name
values (i.e "Mar" matches the value of fieldname
inMonth.MARCH
, while "Marc" or "March" do not) and the format of the sample string you gave us is truly consistent, as in it is no subject to change during runtime and will always remain<day-name> <month> <day> <time> <zone> <year>
where year is always a 4 digit number, the following code should answer give you exactly what you want:Main Class
CustomDateFormat Class
Output
Let me know if this meets your requirements and if any other conditions need to be met or special case scenarios considered. It's a fairly simple implementation so it should take no time to adjust it to more specific needs.
EDIT: Fix some implementation mistakes, change sample string to a custom one and remove redundant output line.