Is there a method in Java that I can use to convert MM/DD/YYYY
to DD-MMM-YYYY
?
For example: 05/01/1999
to 01-MAY-99
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*.
Locale
-sensitiveA Date-Time parsing/formatting type (e.g. DateTimeFormatter
) is Locale
-sensitive i.e. the same letters will produce the text in different Locale
s .e.g. MMM
is used for the three-letter abbreviation of month name and it can be different words in different Locale
s. In the absence of the Locale
parameter, it will use the JVM's Locale
. Therefore, never forget to use a Date-Time parsing/formatting type without the Locale
parameter. Learn more about it from Never use SimpleDateFormat or DateTimeFormatter without a Locale.
You need two instances of DateTimeFormatter
- one to parse the input string and another to format the output string, as per required patterns.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH);
String strDate = "05/01/1999";
LocalDate date = LocalDate.parse(strDate, dtfInput);
// The default string i.e. the value returned by LocalDate#toString
System.out.println(date);
DateTimeFormatter dtfOutputEng = DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.ENGLISH);
String formattedEng = dtfOutputEng.format(date);
System.out.println(formattedEng);
DateTimeFormatter dtfOutputFr = DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.FRENCH);
String formattedFr = dtfOutputFr.format(date);
System.out.println(formattedFr);
}
}
1999-05-01
01-May-1999
01-mai-1999
ONLINE DEMO
Y
(week-based-year), you need to use y
(year-of-era) and instead of D
(day-of-year), you need to use d
(day-of-month). Check the documentation to learn more about it.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.
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