Joda - DateTimeFormatter - 打印一周的日期作为快捷方式

时间:2017-05-04 22:09:40

标签: android datetime string-formatting jodatime datetime-format

我正在使用DateTimeFormatter:

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

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

2 个答案:

答案 0 :(得分:2)

java.time

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

<块引用>

请注意,从 Java SE 8 开始,要求用户迁移到 java.time (JSR-310) - JDK 的核心部分,取代了该项目。

使用 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 中了解有关 Trail: Date Time* 的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 & 7. 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

答案 1 :(得分:0)

这里最好的选择是检查DateTimeFormat.fullDate()的格式,然后使用模式自行重建。{1}}在我的Locale(英语/澳大利亚):

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

相关问题