简体   繁体   English

如何在 Android 中格式化日期和时间?

[英]How to format date and time in Android?

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

Use the standard Java DateFormat class.使用标准的 Java DateFormat 类。

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.您可以使用自己的值初始化 Date 对象,但是您应该知道构造函数已被弃用,您应该真正使用 Java Calendar 对象。

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 - -".在我看来, android.text.format.DateFormat.getDateFormat(context)让我感到困惑,因为此方法返回java.text.DateFormat而不是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 .您可以使用DateFormat Result depends on default Locale of the phone, but you can specify Locale too :结果取决于手机的默认语言环境,但您也可以指定语言环境:

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

This is results on a这是一个结果

DateFormat.getDateInstance().format(date)                                          

FR Locale : 3 nov.法国地区:11 月 3 日。 2017 2017

US/En Locale : Jan 12, 1952美国/英语语言环境:1952 年 1 月 12 日


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

FR Locale : 03/11/2017法国地区:2017 年 3 月 11 日

US/En Locale : 12.13.52美国/英语语言环境:12.13.52


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

FR Locale : 3 nov.法国地区:11 月 3 日。 2017 2017

US/En Locale : Jan 12, 1952美国/英语语言环境:1952 年 1 月 12 日


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

FR Locale : 3 novembre 2017法国地区:2017 年 11 月 3 日

US/En Locale : January 12, 1952美国/英语语言环境:1952 年 1 月 12 日


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

FR Locale : vendredi 3 novembre 2017法国地区:vendredi 2017 年 11 月 3 日

US/En Locale : Tuesday, April 12, 1952美国/英语语言环境:1952 年 4 月 12 日,星期二


DateFormat.getDateTimeInstance().format(date)

FR Locale : 3 nov.法国地区:11 月 3 日。 2017 16:04:58 2017 16:04:58


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

FR Locale : 03/11/2017 16:04法国地区 : 03/11/2017 16:04


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

FR Locale : 03/11/2017 16:04:58法国地区 : 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法国地区: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法国地区:03/11/2017 16:04:58 heure normale d'Europe centrale


DateFormat.getTimeInstance().format(date)

FR Locale : 16:04:58法国地区:16:04:58


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

FR Locale : 16:04法国地区:16:04


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

FR Locale : 16:04:58法国地区:16:04:58


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

FR Locale : 16:04:58 GMT+01:00法国地区:16:04:58 GMT+01:00


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

FR Locale : 16:04:58 heure normale d'Europe centrale FR 地区: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 - > 1969 年 12 月 31 日

   DateFormat.getDateTimeInstance() 

-> Dec 31, 1969 4:00:00 PM -> 1969 年 12 月 31 日下午 4:00:00

   DateFormat.getTimeInstance() 

-> 4:00:00 PM -> 下午 4:00:00

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使用 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如果您正在寻找模式,请查看此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在此之后:http: //developer.android.com/reference/android/text/format/Time.html

Is better to use Android native Time class:最好使用 Android 原生 Time 类:

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:我使用没有自定义模式的 SimpleDateFormat 以设备的预选格式从系统获取实际日期和时间:

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

returns :返回

  • 13.01.15 11:45 13.01.15 11:45
  • 1/13/15 10:45 AM 2015 年 1 月 13 日上午 10:45
  • ... ...

Use build in Time class!在 Time 类中使用 build!

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$ ). %tR%tH:%tM的缩写, <表示重用最后一个参数( 1$ )。

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

https://developer.android.com/reference/java/util/Formatter.html 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 M -> 7, MM -> 07, MMM -> 七月, MMMM -> 七月
  2. EEE -> Tue , EEEE -> Tuesday EEE -> 周二,EEEE -> 周二
  3. z -> EST , zzz -> EST , zzzz -> Eastern Standard Time z -> EST , zzz -> EST , zzzz -> 东部标准时间

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.大多数其他答案中使用的DateDateFormatSimpleDateFormat类早已过时,多年来给许多程序员带来了麻烦。 Today we have so much better in java.time , AKA JSR-310, the modern Java date & time API.今天,我们在java.time ,AKA JSR-310,现代 Java 日期和时间 API 方面有了更好的表现。 Can you use this on Android yet?你可以在Android上使用它吗? Most certainly!最肯定! The modern classes have been backported to Android in the ThreeTenABP project.在 ThreeTenABP 项目中,现代类已被反向移植到 Android。 See this question: How to use ThreeTenABP in Android Project for all the details.有关所有详细信息,请参阅此问题:如何在 Android 项目中使用 ThreeTenABP

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避免juDate

The Java.util.Date and .Calendar and SimpleDateFormat in Java (and Android) are notoriously troublesome. Java(和 Android)中的 Java.util.Date 和 .Calendar 和 SimpleDateFormat 是出了名的麻烦。 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).它们太糟糕了,以至于 Sun/Oracle 放弃了它们,用 Java 8 中的新 java.time 包取代了它们(截至 2014 年在 Android 中没有)。 The new java.time was inspired by the Joda-Time library.新的java.time受到Joda-Time库的启发。

Joda-Time乔达时间

Joda-Time does work in Android. Joda-Time确实适用于 Android。

Search StackOverflow for "Joda" to find many examples and much discussion.在 StackOverflow 中搜索“Joda”以找到许多示例和讨论。

A tidbit of source code using Joda-Time 2.4.使用 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:回到2016年,当我想自定义格式时(不是根据设备配置,如你所问...)我通常使用字符串资源文件:

in strings.xml:在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:在java类中:

    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 android Time 类提供了 3 种格式化方法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这里format是你需要的格式

ex: "HH:mm" returns 15:30例如:“HH:mm”返回 15:30

Date from type类型日期

EEE : Day ( Mon ) MMMM : Full month name ( December ) // MMMM February EEE:日(星期一)MMMM:全月名称(十二月)//MMMM 二月
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 ) MMM : 用文字表示的月份 (Dec) MM: 月份 (12) dd: 2 个字符的日期 (03) d: 1 个字符的日期 (3) HH: 小时 (12) mm: 分钟 (50) ss: 秒 (34) yyyy: 年 (2020) //yyyy 和 YYYY 都相同 YYYY: 年 (2020) zzz : GMT+05:30 a : ( AM / PM ) aa : ( AM / PM ) aaa : ( AM / PM ) aaaa : ( 上午下午 )

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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