JodaTime DateTime format with preferred DateFormat

I use Joda Time and should display the date in my preferred user format ( note that before Android M the format could be changed ).

Joda DateTime can be formatted using DateTimeFormatter, which is created from a string with the desired date format:

public String getFormattedDate(String datePattern) {
    if (mDate != null) {
        // get your local timezone
        DateTimeZone localTZ = DateTimeZone.getDefault();
        DateTime dt = mDate.toDateTime(localTZ);

        DateTimeFormatter fmt = DateTimeFormat.forPattern(datePattern);
        String formattedDate = dt.toString(fmt);
        return formattedDate;
    }
    return "";
}

but to get your preferred user format, you have to use Java DateFormat:

public static DateFormat getPreferredDateFormat(Context context) {
    final String format = Settings.System.getString(context.getContentResolver(), Settings.System.DATE_FORMAT);
    DateFormat dateFormat;
    if (android.text.TextUtils.isEmpty(format)) {
        dateFormat = android.text.format.DateFormat.getMediumDateFormat(context.getApplicationContext());
    } else {
        dateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext()); // Gets system date format
    }

    if (dateFormat == null)
        dateFormat = new SimpleDateFormat(format);

    return dateFormat;
}

And Java DateFormat does not have a method that can give me a String with the date format in it.

So, is there a way to format a Joda DateTime date with a Java DateFormat? And perhaps also indicate that I want to show only the day and month (will there be dd / MM or MM / dd)? Or to make DateTimeFormatter preferable for the user?

+4
2

DateFormat , , ( ). , android.text.format.DateFormat.getDateFormat(), SimpleDateFormat, . - :

SimpleDateFormat format=(SimpleDateFormat)DateFormat.getDateFormat(context.getApplicationContext());
String pattern=format.toPattern();

String pattern=format.toLocalizedPattern();

, , 100% , , getDateFormat(), .

+2

java.time

Joda-Time . java.time.

DateTimeFormatter , .

Instant instant = Instant.now();  // Current moment in UTC with a resolution of up to nanoseconds.
ZoneId z = ZoneId.of( "America/Montreal" );  // Specify a time zone.
ZonedDateTime zdt = instant.atZone( z );  // Adjust from UTC to a specific time zone. Same moment, different wall-clock time.

, :

:

Locale l = Locale.CANADA_FRENCH ; 
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );

, MonthDay .

MonthDay md = MonthDay.from( zdt );

java.time

java.time Java 8 . , java.util.Date, .Calendar java.text.SimpleDateFormat.

Joda-Time, , java.time.

, . Oracle. Qaru .

java.time Java 6 7 ThreeTen-Backport Android ThreeTenABP (. ...).

ThreeTen-Extra java.time . java.time. , Interval, YearWeek, YearQuarter ..

0

Source: https://habr.com/ru/post/1653490/


All Articles