简体   繁体   中英

How to format date and time in Android?

有年月日时分时,如何根据设备配置日期和时间正确格式化?

Use the standard Java DateFormat class.

For example to display the current date and time do the following:

Date date = new Date(location.getTime());
DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));

You can initialise a Date object with your own values, however you should be aware that the constructors have been deprecated and you should really be using a Java Calendar object.

In my opinion, android.text.format.DateFormat.getDateFormat(context) makes me confused because this method returns java.text.DateFormat rather than android.text.format.DateFormat - -".

So, I use the fragment code as below to get the current date/time in my format.

android.text.format.DateFormat df = new android.text.format.DateFormat();
df.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());

or

android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss a", new java.util.Date());

In addition, you can use others formats. Follow DateFormat .

You can use DateFormat . Result depends on default Locale of the phone, but you can specify Locale too :

https://developer.android.com/reference/java/text/DateFormat.html

This is results on a

DateFormat.getDateInstance().format(date)                                          

FR Locale : 3 nov. 2017

US/En Locale : Jan 12, 1952


DateFormat.getDateInstance(DateFormat.SHORT).format(date)

FR Locale : 03/11/2017

US/En Locale : 12.13.52


DateFormat.getDateInstance(DateFormat.MEDIUM).format(date)

FR Locale : 3 nov. 2017

US/En Locale : Jan 12, 1952


DateFormat.getDateInstance(DateFormat.LONG).format(date)

FR Locale : 3 novembre 2017

US/En Locale : January 12, 1952


DateFormat.getDateInstance(DateFormat.FULL).format(date)

FR Locale : vendredi 3 novembre 2017

US/En Locale : Tuesday, April 12, 1952


DateFormat.getDateTimeInstance().format(date)

FR Locale : 3 nov. 2017 16:04:58


DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(date)

FR Locale : 03/11/2017 16:04


DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(date)

FR Locale : 03/11/2017 16:04:58


DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG).format(date)

FR Locale : 03/11/2017 16:04:58 GMT+01:00


DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL).format(date)

FR Locale : 03/11/2017 16:04:58 heure normale d'Europe centrale


DateFormat.getTimeInstance().format(date)

FR Locale : 16:04:58


DateFormat.getTimeInstance(DateFormat.SHORT).format(date)

FR Locale : 16:04


DateFormat.getTimeInstance(DateFormat.MEDIUM).format(date)

FR Locale : 16:04:58


DateFormat.getTimeInstance(DateFormat.LONG).format(date)

FR Locale : 16:04:58 GMT+01:00


DateFormat.getTimeInstance(DateFormat.FULL).format(date)

FR Locale : 16:04:58 heure normale d'Europe centrale


Date to Locale date string:

Date date = new Date();
String stringDate = DateFormat.getDateTimeInstance().format(date);

Options:

   DateFormat.getDateInstance() 

- > Dec 31, 1969

   DateFormat.getDateTimeInstance() 

-> Dec 31, 1969 4:00:00 PM

   DateFormat.getTimeInstance() 

-> 4:00:00 PM

This will do it:

Date date = new Date();
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));

Use SimpleDateFormat

Like this:

event.putExtra("starttime", "12/18/2012");

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date = format.parse(bundle.getString("starttime"));

Here is the simplest way:

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US);

    String time = df.format(new Date());

and If you are looking for patterns , check this https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Date and Time format explanation

EEE : Day ( Mon )
MMMM : Full month name ( December ) // MMMM February   
MMM : Month in words ( Dec )
MM : Month ( 12 )
dd : Day in 2 chars ( 03 )
d: Day in 1 char (3)
HH : Hours ( 12 )
mm : Minutes ( 50 )
ss : Seconds ( 34 )
yyyy: Year ( 2020 ) //both yyyy and YYYY are same
YYYY: Year ( 2020 )
zzz : GMT+05:30
a : ( AM / PM )
aa : ( AM / PM )
aaa : ( AM / PM )
aaaa : ( AM / PM )

Following this: http://developer.android.com/reference/android/text/format/Time.html

Is better to use Android native Time class:

Time now = new Time();
now.setToNow();

Then format:

Log.d("DEBUG", "Time "+now.format("%d.%m.%Y %H.%M.%S"));

Use these two as a class variables:

 public java.text.DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
 private Calendar mDate = null;

And use it like this:

 mDate = Calendar.getInstance();
 mDate.set(year,months,day);                   
 dateFormat.format(mDate.getTime());

This is my method, you can define and input and output format.

public static String formattedDateFromString(String inputFormat, String outputFormat, String inputDate){
    if(inputFormat.equals("")){ // if inputFormat = "", set a default input format.
        inputFormat = "yyyy-MM-dd hh:mm:ss";
    }
    if(outputFormat.equals("")){
        outputFormat = "EEEE d 'de' MMMM 'del' yyyy"; // if inputFormat = "", set a default output format.
    }
    Date parsed = null;
    String outputDate = "";

    SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, java.util.Locale.getDefault());
    SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, java.util.Locale.getDefault());

    // You can set a different Locale, This example set a locale of Country Mexico.
    //SimpleDateFormat df_input = new SimpleDateFormat(inputFormat, new Locale("es", "MX"));
    //SimpleDateFormat df_output = new SimpleDateFormat(outputFormat, new Locale("es", "MX"));

    try {
        parsed = df_input.parse(inputDate);
        outputDate = df_output.format(parsed);
    } catch (Exception e) { 
        Log.e("formattedDateFromString", "Exception in formateDateFromstring(): " + e.getMessage());
    }
    return outputDate;

}

SimpleDateFormat

I use SimpleDateFormat without custom pattern to get actual date and time from the system in the device's preselected format:

public static String getFormattedDate() {
    //SimpleDateFormat called without pattern
    return new SimpleDateFormat().format(Calendar.getInstance().getTime());
}

returns :

  • 13.01.15 11:45
  • 1/13/15 10:45 AM
  • ...

Use build in Time class!

Time time = new Time();
time.set(0, 0, 17, 4, 5, 1999);
Log.i("DateTime", time.format("%d.%m.%Y %H:%M:%S"));

Shortest way:

// 2019-03-29 16:11
String.format("%1$tY-%<tm-%<td %<tR", Calendar.getInstance())

%tR is short for %tH:%tM , < means to reuse last parameter( 1$ ).

It is equivalent to String.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM", Calendar.getInstance())

https://developer.android.com/reference/java/util/Formatter.html

Date format class work with cheat code to make date. Like

  1. M -> 7, MM -> 07, MMM -> Jul , MMMM -> July
  2. EEE -> Tue , EEEE -> Tuesday
  3. z -> EST , zzz -> EST , zzzz -> Eastern Standard Time

You can check more cheats here .

This code work for me!

Date d = new Date();
    CharSequence s = android.text.format.DateFormat.format("MM-dd-yy hh-mm-ss",d.getTime());
    Toast.makeText(this,s.toString(),Toast.LENGTH_SHORT).show();

The other answers are generally correct. I should like to contribute the modern answer. The classes Date , DateFormat and SimpleDateFormat used in most of the other answers, are long outdated and have caused trouble for many programmers over many years. Today we have so much better in java.time , AKA JSR-310, the modern Java date & time API. Can you use this on Android yet? Most certainly! The modern classes have been backported to Android in the ThreeTenABP project. See this question: How to use ThreeTenABP in Android Project for all the details.

This snippet should get you started:

    int year = 2017, month = 9, day = 28, hour = 22, minute = 45;
    LocalDateTime dateTime = LocalDateTime.of(year, month, day, hour, minute);
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
    System.out.println(dateTime.format(formatter));

When I set my computer's preferred language to US English or UK English, this prints:

Sep 28, 2017 10:45:00 PM

When instead I set it to Danish, I get:

28-09-2017 22:45:00

So it does follow the configuration. I am unsure exactly to what detail it follows your device's date and time settings, though, and this may vary from phone to phone.

Locale

To get date or time in locale format from milliseconds I used this:

Date and time

Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault());
dateFormat.format(date);

Date

Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault());
dateFormat.format(date);

Time

Date date = new Date(milliseconds);
DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
dateFormat.format(date);

You can use other date style and time style. More info about styles here .

This code would return the current date and time:

public String getCurrDate()
{
    String dt;
    Date cal = Calendar.getInstance().getTime();
    dt = cal.toLocaleString();
    return dt;
}

I use it like this:

public class DateUtils {
    static DateUtils instance;
    private final DateFormat dateFormat;
    private final DateFormat timeFormat;

    private DateUtils() {
        dateFormat = android.text.format.DateFormat.getDateFormat(MainApplication.context);
        timeFormat = android.text.format.DateFormat.getTimeFormat(MainApplication.context);
    }

    public static DateUtils getInstance() {
        if (instance == null) {
            instance = new DateUtils();
        }
        return instance;
    }

    public synchronized static String formatDateTime(long timestamp) {
        long milliseconds = timestamp * 1000;
        Date dateTime = new Date(milliseconds);
        String date = getInstance().dateFormat.format(dateTime);
        String time = getInstance().timeFormat.format(dateTime);
        return date + " " + time;
    }
}

Try:

event.putExtra("startTime", "10/05/2012");

And when you are accessing passed variables:

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(bundle.getString("startTime"));

Avoid juDate

The Java.util.Date and .Calendar and SimpleDateFormat in Java (and Android) are notoriously troublesome. Avoid them. They are so bad that Sun/Oracle gave up on them, supplanting them with the new java.time package in Java 8 (not in Android as of 2014). The new java.time was inspired by the Joda-Time library.

Joda-Time

Joda-Time does work in Android.

Search StackOverflow for "Joda" to find many examples and much discussion.

A tidbit of source code using Joda-Time 2.4.

Standard format.

String output = DateTime.now().toString(); 
// Current date-time in user's default time zone with a String representation formatted to the ISO 8601 standard.

Localized format.

String output = DateTimeFormat.forStyle( "FF" ).print( DateTime.now() ); 
// Full (long) format localized for this user's language and culture.

Back to 2016, When I want to customize the format (not according to the device configuration, as you ask...) I usually use the string resource file:

in strings.xml:

<string name="myDateFormat"><xliff:g id="myDateFormat">%1$td/%1$tm/%1$tY</xliff:g></string>

In Activity:

Log.d(TAG, "my custom date format: "+getString(R.string.myDateFormat, new Date()));

This is also useful with the release of the new Date Binding Library .

So I can have something like this in layout file:

<TextView
    android:id="@+id/text_release_date"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:padding="2dp"
    android:text="@{@string/myDateFormat(vm.releaseDate)}"
    tools:text="0000"
    />

And in java class:

    MovieDetailViewModel vm = new MovieDetailViewModel();
    vm.setReleaseDate(new Date());

The android Time class provides 3 formatting methods http://developer.android.com/reference/android/text/format/Time.html

This is how I did it:

/**
* This method will format the data from the android Time class (eg. myTime.setToNow())   into the format
* Date: dd.mm.yy Time: hh.mm.ss
*/
private String formatTime(String time)
{
    String fullTime= "";
    String[] sa = new String[2];

    if(time.length()>1)
    {
        Time t = new Time(Time.getCurrentTimezone());
        t.parse(time);
        // or t.setToNow();
        String formattedTime = t.format("%d.%m.%Y %H.%M.%S");
        int x = 0;

        for(String s : formattedTime.split("\\s",2))
        {   
            System.out.println("Value = " + s);
            sa[x] = s;
            x++;
        }
        fullTime = "Date: " + sa[0] + " Time: " + sa[1];
    }
    else{
        fullTime = "No time data";
    }
    return fullTime;
}

I hope thats helpful :-)

It's too late but it may help to someone

DateFormat.format(format, timeInMillis);

here format is what format you need

ex: "HH:mm" returns 15:30

Date from type

EEE : Day ( Mon ) MMMM : Full month name ( December ) // MMMM February
MMM : Month in words ( Dec ) MM : Month ( 12 ) dd : Day in 2 chars ( 03 ) d: Day in 1 char (3) HH : Hours ( 12 ) mm : Minutes ( 50 ) ss : Seconds ( 34 ) yyyy: Year ( 2020 ) //both yyyy and YYYY are same YYYY: Year ( 2020 ) zzz : GMT+05:30 a : ( AM / PM ) aa : ( AM / PM ) aaa : ( AM / PM ) aaaa : ( AM / PM )

当具有年,月,日,小时和分钟时,如何根据设备配置日期和时间正确格式化?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM