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";
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With