0

I want to get the current Date Format of Android emulator. Can anyone help me?

Not like this

SimpleDateFormat FormattedDATE = new SimpleDateFormat("M-d-yyyy");      
Calendar cal = Calendar.getInstance();
Community
  • 1
  • 1
Kenjoe
  • 21
  • 1

2 Answers2

2

There are various options:

DateFormat defaultFormat = DateFormat.getDateInstance();
DateFormat longFormat = DateFormat.getDateInstance(DateFormat.LONG);
DateFormat mediumFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
// etc

And likewise for getDateTimeInstance.

Basically look at the static methods of DateFormat that return instances of DateFormat.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

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:

DateTimeFormatter#ofLocalizedDate provides a formatter that uses the locale-specific date format.

Demo:

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now(ZoneId.of("America/New_York"));

        DateTimeFormatter shortDateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
                                                .localizedBy(Locale.ENGLISH);
        System.out.println(shortDateFormatter.format(today));

        DateTimeFormatter mediumDateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
                                                .localizedBy(Locale.ENGLISH);
        System.out.println(mediumDateFormatter.format(today));

        DateTimeFormatter longDateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
                                                .localizedBy(Locale.ENGLISH);
        System.out.println(longDateFormatter.format(today));
    }
}

Output:

7/13/21
Jul 13, 2021
July 13, 2021

ONLINE DEMO

Change the ZoneId and the Locale as applicable.

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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110