如何在Java (android) 中自定义SimpleDateFormat() 的日期格式?

How to customize date format of SimpleDateFormat() in Java (android)?

在我的 PHP 网页中,我使用了这段代码(如下所示),它以我想要的格式给出了当天的日期,即(示例)2021 年 10 月 2 日.

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

现在,我想用 Java 实现同样的效果 - 当我尝试在 Java (android) 中添加格式 jS M\. Y 时,它显示了一些错误我无法理解...这是我在 Java -

中尝试过的内容
String date = new SimpleDateFormat("jS M\. Y", Locale.getDefault()).format(new Date());

我目前是 Java 的新手,刚刚发现这个 class,所以我不知道很多事情我应该怎么做才能在我的日期中获取当天的日期想要的格式?请指导我...谢谢!

这是否满足您的要求?

String date = new SimpleDateFormat("dd MMM yyyy", Locale.getDefault()).format(new Date());

java.time

java.util 日期时间 API 及其格式 API、SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到 modern Date-Time API*.

解决方案使用 java.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;
    }
}

输出:

2nd Oct. 2021

ONLINE DEMO

Trail: Date Time.

了解有关现代日期时间 API 的更多信息

更新

来自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.


* 无论出于何种原因,如果您必须坚持Java 6 或Java 7,您可以使用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