Problems with your code:
- The pattern for parsing should match with the given date-time string. You have missed
'T'
in the pattern for parsing.
- Also, you have used
M
instead of m
for "Minute in hour". The symbol, M
is used for "Month in year". Read the documentation carefully.
Demo with correct patterns:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
String date = "2021-05-14T09:26:20";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date newDate = parser.parse(date);
System.out.println(format.format(newDate));
}
}
ONLINE DEMO
Introducing java.time
, the modern Date-Time API:
Note that the java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*, released in March 2014 as part of Java SE 8 standard library.
Solution using java.time
, the modern Date-Time API:
The modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter
object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String date = "2021-05-14T09:26:20";
LocalDateTime ldt = LocalDateTime.parse(date);
System.out.println(ldt);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
System.out.println(dtf.format(ldt));
}
}
Output:
2021-05-14T09:26:20
2023-02-14 09:02:20
ONLINE DEMO
Here, you can use y
instead of u
but I prefer u
to y
.
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.