2

In my PHP webpage, I used this code (given below), which gives me the day's date in my desired format, which is (example) 2nd Oct. 2021.

<?php
date_default_timezone_set('Asia/Calcutta');
echo date('jS M\. Y'); //result = 2nd Oct. 2021
?>

Now, I want to achieve the same with Java - when I tried adding the format jS M\. Y in Java (android), it showed me some errors I'm unable to understand... Here's what I've tried in Java -

String date = new SimpleDateFormat("jS M\. Y", Locale.getDefault()).format(new Date());

I am currently new to Java & just found out about this class, so I don't know a lot of things What should I do in order to get the day's date in my desired format? Please guide me... Thanks!

Sonal
  • 137
  • 2
  • 13
  • Refer to _javadoc_ for class [java.text.SimpleDateFormat](https://developer.android.com/reference/java/text/SimpleDateFormat) However, if your java version is compatible with at least Java 8, it is recommended to work with the [date-time API](https://docs.oracle.com/javase/tutorial/datetime/index.html) – Abra Oct 02 '21 at 06:17

2 Answers2

4

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:

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.now(ZoneId.of("Asia/Kolkata"));
        DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                                .appendText(ChronoField.DAY_OF_MONTH, ordinalMap())
                                .appendPattern(" MMM. uuuu")
                                .toFormatter(Locale.ENGLISH);
        String output = date.format(dtf);
        System.out.println(output);
    }

    static Map<Long, String> ordinalMap() {
        String[] suffix = { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
        Map<Long, String> map = new HashMap<>();

        for (int i = 1; i <= 31; i++)
            map.put((long) i, String.valueOf(i) + suffix[(i > 3 && i < 21) ? 0 : (i % 10)]);

        return map;
    }
}

Output:

2nd Oct. 2021

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


Update

A valuable comment from Joachim Sauer:

Since this is tagged as Android, it should be noted that java.time is available in Android since 8.0 (Oreo) and most of it can be accessed even when targeting older versions through desugaring.


* 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
  • 2
    Since this is tagged as Android, it should be noted that `java.time` is available [in Android since 8.0 (Oreo)](https://developer.android.com/reference/java/time/package-summary) and most of it can be accessed even when targeting older versions [through desugaring](https://developer.android.com/studio/write/java8-support-table). – Joachim Sauer Oct 02 '21 at 11:10
  • 2
    Thanks, @JoachimSauer for the valuable information. I've incorporated it into my answer because sometimes comments get deleted. – Arvind Kumar Avinash Oct 02 '21 at 11:14
  • 1
    Thanks @ArvindKumarAvinash! Your approach works perfectly for me - you're the best! Thanks a lot again – Sonal Oct 02 '21 at 12:23
0

Does this satisfy your requirements?

String date = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault()).format(new Date());
Eyosiyas
  • 1,422
  • 1
  • 9
  • 25