java.time
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*.
Solution using java.time
, the modern Date-Time API:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd, uuuu 'at' h:mm a", new Locale("vi", "VN"));
System.out.println(LocalDateTime.of(2021, 8, 4, 10, 20).format(dtf));
System.out.println(LocalDateTime.of(2021, 8, 4, 20, 30).format(dtf));
}
}
Output from a sample run:
thg 8 04, 2021 at 10:20 SA
thg 8 04, 2021 at 8:30 CH
ONLINE DEMO
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.