String To Date Format Java
Solution 1:
The legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time
, the modern date-time API.
Using modern date-time API:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
publicclassMain {
publicstaticvoidmain(String[] args) {
StringstrDateTime="2021-04-25T18:54:18";
LocalDateTimeldt= LocalDateTime.parse(strDateTime);
DateTimeFormatterdtfOutput= DateTimeFormatter.ofPattern("HH:mm ,dd MMM yyyy", Locale.ENGLISH);
Stringoutput= dtfOutput.format(ldt);
System.out.println(output);
}
}
Output:
18:54 ,25 Apr 2021
Learn more about the modern date-time API from Trail: Date Time.
Using the legacy API:
You need two formatters: one for input pattern and one for output pattern. You didn't need two formatters in the case of the modern API because the modern API is based on ISO 8601 and your date-time string is already in this format.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
publicclassMain {
publicstaticvoidmain(String[] args)throws ParseException {
StringstrDateTime="2021-04-25T18:54:18";
SimpleDateFormatsdfInput=newSimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
Datedate= sdfInput.parse(strDateTime);
SimpleDateFormatsdfOutput=newSimpleDateFormat("HH:mm ,dd MMM yyyy", Locale.ENGLISH);
Stringoutput= sdfOutput.format(date);
System.out.println(output);
}
}
Output:
18:54 ,25 Apr 2021
Solution 2:
You are missing 1 step. SimpleDateFormat
can only parse dates in the format you specify.
You are trying to parse a "yyyy-MM-dd ..." based string into the "HH:mm ..." date. This will not work.
First convert your "yyyy-MM-dd" date string into a Date. Then, format that Date into the String you need
String input = "2021-04-25T18:54:18";
Datedate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH).parse(input);
String output = new SimpleDateFormat("HH:mm, yyyy-MM-dd", Locale.ENGLISH).format(date);
Post a Comment for "String To Date Format Java"