Suman Radhakrishnan
Suman Radhakrishnan

Reputation: 668

Simple Date Format for the Following Values in Android

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

Upvotes: 0

Views: 315

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79075

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.

Upvotes: 3

Related Questions