Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

format date from 14 aug to YYYYMMDD

Tags:

java

date

format

Change the date 14 aug 2011 to the format 20110814 .. how can i do that in java ?

Here 14aug is a string ... String date="14aug";

like image 805
Praneel PIDIKITI Avatar asked Nov 28 '22 04:11

Praneel PIDIKITI


2 Answers

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String yyyyMMdd = sdf.format(date);

Reference: java.text.SimpleDateFormat

Update: the question by The Elite Gentleman is important. If you start with a String, then you should first parse it to obtain the date object from the above example:

Date date = new SimpleDateFormat("dd MMM yyyy").parse(dateString);
like image 188
Bozho Avatar answered Dec 04 '22 12:12

Bozho


The other answers were good answers in 2011 when they were written. Time moves on. Today no one should use the now long outdated classes SimpleDateFormat and Date. The modern answer uses the java.time classes:

    String date = "14 aug 2011";
    DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("dd MMM uuuu")
            .toFormatter(Locale.ENGLISH);
    System.out.println(LocalDate.parse(date, parseFormatter)
                        .format(DateTimeFormatter.BASIC_ISO_DATE));

This prints the desired:

20110814

The modern parsing mechanism is somewhat stricter because experience shows that the old one was way too lenient and often produced surprising results in situations where one would have expected an error message. For example, the modern one requires correct case, that is, capital A in Aug in English, unless we tell it that it should parse without case sensitivity. So this is what I am doing with the parseCaseInsensitive(). The call affects the following builder method calls, so we have to place it before appendPattern().

Edit: Taking your string "14aug" from the question literally. SimpleDateFormat would have used 1970 as default year (year of the epoch), giving you trouble how to get the correct year. The modern classes allow you to specify a default year explicitly, for example:

    String date = "14aug";
    DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("ddMMM")
            .parseDefaulting(ChronoField.YEAR, Year.now(ZoneId.systemDefault()).getValue())
            .toFormatter(Locale.ENGLISH);

With this change, running the code today we get:

20170814

Edit 2: Now using DateTimeFormatter.BASIC_ISO_DATE for formatting as recommended in Basil Bourque’s answer.

like image 37
Ole V.V. Avatar answered Dec 04 '22 12:12

Ole V.V.