Joda - DateTimeFormatter - 打印星期几作为快捷方式

Joda - DateTimeFormatter - print day of a week as a shortcut

我正在使用 DateTimeFormatter:

DateTimeFormatter dateTimeFormatter = DateTimeFormat.fullDate();
dateTimeFormatter.print(...);

我需要打印完整日期,但星期几应该显示为快捷方式。可能吗?

这里最好的办法是检查 DateTimeFormat.fullDate() 的格式,然后自己使用模式重建它。在我的语言环境中(English/Australia):

DateTimeFormatter dtf = DateTimeFormat.fullDate();
System.out.println(dtf.print(DateTime.now()));
//result: Sunday, May 7, 2017

所以我会使用以下模式来获取星期几的缩写:

DateTimeFormatter dtf = DateTimeFormat.forPattern("E, MMM d, YYYY");
System.out.println(dtf.print(DateTime.now()));
//result: Sun, May 7, 2017

请注意,"E" 和 "EEE" 是星期几的缩写和星期几的两种模式。请参阅 javadoc for DateTimeFormat 以获取模式列表

java.time

下面引用的是 Home Page of Joda-Time:

的通知

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

解决方案使用 java.time,现代日期时间 API:

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

public class Main {
    public static void main(String[] a) {
        // Replace ZoneId.systemDefault(), which specifies the JVM's default time zone,
        // as applicable e.g. ZoneId.of("Europe/London")
        LocalDate today = LocalDate.now(ZoneId.systemDefault());

        // 1. Using DayOfWeek
        // Replace Locale.ENGLISH as per the desired Locale
        String dayName = today.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.ENGLISH);
        System.out.println(dayName);

        // 2. Using DateTimeFormatter
        // Replace Locale.ENGLISH as per the desired Locale
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("E", Locale.ENGLISH);
        dayName = dtf.format(today);
        System.out.println(dayName);
    }
}

输出:

Tue
Tue

详细了解 modern date-time API* from Trail: Date Time


* 无论出于何种原因,如果您必须坚持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