RominaV
RominaV

Reputation: 3415

Format JodaTime DateTime with preferred DateFormat

I'm using Joda Time and need to display a date in the user's preferred format (note that before Android M, the format could be changed).

A 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 the user's preferred 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 doesn't have a method which can give me a String with a date format in it.

So is there a way to format a Joda DateTime with Java DateFormat? And maybe also specify that I only want to show day and month (would be dd/MM or MM/dd) ? Or to make DateTimeFormatter take the user's preferred format?

Upvotes: 6

Views: 1401

Answers (3)

Abdifatah Mohamed
Abdifatah Mohamed

Reputation: 357

private String getCurrentDate() {
    DateTime dateTimeUtc = new DateTime( DateTimeZone.UTC );

    DateTimeZone timeZone = DateTimeZone.forID( "Africa/Khartoum" );
    
    java.util.Locale locale = new Locale( "ar", "SD" ); // ( language code, country code );
    DateTimeFormatter formatter = DateTimeFormat.forStyle( "FF" ).withLocale( locale ).withZone( timeZone );
    String output = formatter.print( dateTimeUtc );


    return  output.substring(output.indexOf(output.charAt(0)),output.indexOf(':') - 2);
}

Upvotes: 0

Basil Bourque
Basil Bourque

Reputation: 338624

java.time

The Joda-Time project is now in maintenance mode. The team advises moving to the java.time classes.

The DateTimeFormatter class can automatically localize when generating a String representing a date-time value.

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.

To localize, specify:

  • FormatStyle to determine long or abbreviated should the string be.
  • Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.

Example:

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

If you want to work with just the month and day-of-month, the MonthDay class goes just that.

MonthDay md = MonthDay.from( zdt );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Upvotes: 1

Markus Fischer
Markus Fischer

Reputation: 1366

DateFormat is an abstract class, and as such doesn't have an access method to the format pattern (as each concrete implementation will handle its own pattern). However, what android.text.format.DateFormat.getDateFormat() returns is actually a SimpleDateFormat, which provides the pattern. Therefore you can do something like:

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

or

String pattern=format.toLocalizedPattern();

This works for the time being, but please note that it's not 100% future proof, as the actual class returned by getDateFormat() may change in the future.

Upvotes: 3

Related Questions