0

Please provide the Simple Date format for the following in android

The DateFormat of 21/08/2021 -> SimpleDateFormat("dd/MM/yyyy")

I Want the SimpleDateFormat for the following two Values

The DateFormat of January 01, 2021 at 3:37:59 PM UTC+5:30 -> SimpleDateFormat("?")

The DateFormat of Wed Sep 15 10:10:59 GMT+05:30 2021 -> SimpleDateFormat("?")

Thanks in advance

  • 1
    Why don't you use `java.time`? – deHaar Sep 15 '21 at 14:45
  • If you know upfront the several possible formats the input can take, then I would recommend bundling them all into a `DateTimeFormatterBuilder` and using that. – PPartisan Sep 15 '21 at 14:59
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. See if you either can use [desugaring](https://developer.android.com/studio/write/java8-support-table) or add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project, in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Sep 15 '21 at 17:03

1 Answers1

3

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:

  1. For the first format, you can build the required DateTimeFormatter using the DateTimeFormatterBuilder.
  2. For the second pattern, you can simply use DateTimeFormatter with the required pattern letters.

Demo:

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));

        DateTimeFormatter dtf1 = 
                new DateTimeFormatterBuilder()
                .appendPattern("MMMM dd, uuuu 'at' h:mm:ss a 'UTC'")
                .appendOffset("+H:mm", "Z")
                .toFormatter(Locale.ENGLISH);
        
        System.out.println(now.format(dtf1));

        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss OOOO uuuu", Locale.ENGLISH);
        System.out.println(now.format(dtf2));
    }
}

Output:

September 15, 2021 at 10:22:43 PM UTC+5:30
Wed Sep 15 22:22:43 GMT+05:30 2021

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.

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