Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Going from MM/DD/YYYY to DD-MMM-YYYY in java

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

like image 501
javan_novice Avatar asked Nov 12 '10 22:11

javan_novice


1 Answers

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*.

A Date-Time parsing/formatting type is Locale-sensitive

A Date-Time parsing/formatting type (e.g. DateTimeFormatter) is Locale-sensitive i.e. the same letters will produce the text in different Locales .e.g. MMM is used for the three-letter abbreviation of month name and it can be different words in different Locales. 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.

Demo:

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);
    }
}

Output:

1999-05-01
01-May-1999
01-mai-1999

ONLINE DEMO

Some other important notes:

  1. Instead of 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.
  2. 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.

like image 72
Arvind Kumar Avinash Avatar answered Sep 18 '22 14:09

Arvind Kumar Avinash