0

I'm using DateTimeFormatter:

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

I need to print full date but the day of a week should be displayed as a shortcut. Is it possible?

AppiDevo
  • 3,195
  • 3
  • 33
  • 51

2 Answers2

2

java.time

Quoted below is a notice at the 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.

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.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);
    }
}

Output:

Tue
Tue

Learn more about the 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.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

Your best bet here is to inspect the format of DateTimeFormat.fullDate() and then reconstruct it yourself using a pattern. In my Locale (English/Australia):

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

So I would use the following pattern to get the abbreviated day of week:

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

Note that "E" and "EEE" are the two patterns for abbreviated day of week and full day of week. Refer to the javadoc for DateTimeFormat for a list of patterns

David Rawson
  • 20,912
  • 7
  • 88
  • 124
  • How can I inspect and reconstruct when DateTimeFormatter works on different Locales (Android) ? – AppiDevo May 07 '17 at 01:28
  • @AppiDevo use https://developer.android.com/reference/android/text/format/DateUtils.html rather than joda if you want that – David Rawson May 07 '17 at 01:32