【问题标题】:How to format date and time in Android?如何在 Android 中格式化日期和时间?
【发布时间】:2010-10-02 01:03:34
【问题描述】:

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

【问题讨论】:

    标签: android date time formatting format


    【解决方案1】:

    使用标准的 Java DateFormat 类。

    例如,要显示当前日期和时间,请执行以下操作:

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

    您可以使用自己的值初始化 Date 对象,但是您应该知道构造函数已被弃用,您应该真正使用 Java Calendar 对象。

    【讨论】:

    • 这是 android.text.format.DateFormat 而不是 java.text.DateFormat。
    • Android IME 非常典型,有两个类都声称可以为您提供设置为默认语言环境的结果,但一个没有。所以是的,不要忘记使用 DateFormat 的 android.text.format 版本(甚至没有派生 java.util 一个 LOL)。
    • 请注意这一行:DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext()); 返回的 dateFormat 类型为 java.text.DateFormat(而不是 android.text.format.DateFormat
    • @Harsha - 为了解决这个问题,我链接了我对 DateFormat 的使用,所以我只需要引用 Android 类,因此没有任何模棱两可的类。 final String dateStr = DateFormat.getDateFormat(this).format(d);您可以使用 Android 的 format() 方法并拥有(恕我直言)更简洁的代码和一个要实例化的对象。
    • 此格式化程序仅包括日期,而不是原始问题所述的时间。请改用同一个包中的 DateUtils,请参阅 stackoverflow.com/questions/2983920/…
    【解决方案2】:

    在我看来,android.text.format.DateFormat.getDateFormat(context) 让我感到困惑,因为此方法返回 java.text.DateFormat 而不是 android.text.format.DateFormat - -"。

    所以,我使用下面的片段代码以我的格式获取当前日期/时间。

    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());
    

    此外,您还可以使用其他格式。关注DateFormat

    【讨论】:

    • 有用,但问题说“根据设备配置”。对我来说,这意味着使用基于用户语言/国家/地区选择的格式,或者由用户直接选择的格式,而不是硬编码格式的选择。
    • 另外,别忘了hh:mm:ss 会在下午 1 点给你01:00:00,你需要使用kk:mm:ss 来获得13:00:00
    • @dnet k 是一天中的小时(1-24),你不是说H,它是一天中的小时(0-23),例如。 HH:mm:ss?见:developer.android.com/reference/java/text/SimpleDateFormat.html
    • @Joony 不,java.text.SimpleDateFormat(您链接的内容并在 0-23 范围内使用 H)和 android.text.format.DateFormat(答案是关于并使用 @987654336 @ 表示 0-23 范围内的小时数)
    • @dnet 经过测试,您对k 是正确的,但是DateFormat 的文档明确指出有关格式字符串的规范文档,请参阅 SimpleDateFormat。 非常令人困惑。还是我错过了什么?
    【解决方案3】:

    您可以使用DateFormat。结果取决于手机的默认语言环境,但您也可以指定语言环境:

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

    这是一个结果

    DateFormat.getDateInstance().format(date)                                          
    

    法国地区:11 月 3 日。 2017

    美国/英语语言环境:1952 年 1 月 12 日


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

    法国地区:2017 年 3 月 11 日

    美国/英语区域设置:12.13.52


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

    法国地区:11 月 3 日。 2017

    美国/英语语言环境:1952 年 1 月 12 日


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

    法国地区:2017 年 11 月 3 日

    美国/英语语言环境:1952 年 1 月 12 日


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

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

    美国/英语语言环境:1952 年 4 月 12 日,星期二


    DateFormat.getDateTimeInstance().format(date)
    

    法国地区:11 月 3 日。 2017 16:04:58


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

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


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

    法国地区:03/11/2017 16:04:58


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

    法国地区:2017 年 3 月 11 日 16:04:58 GMT+01:00


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

    法国地区:03/11/2017 16:04:58 heure normale d'Europe centrale


    DateFormat.getTimeInstance().format(date)
    

    法国地区:16:04:58


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

    法国地区:16:04


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

    法国地区:16:04:58


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

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


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

    法国地区:16:04:58 heure normale d'Europe centrale


    【讨论】:

    • 感谢您将所有这些案例放在一个地方。如果您也可以仅添加时间案例,这将使其成为完整的参考。
    • 我在问为什么文档不是那么 esaustive,非常感谢
    【解决方案4】:

    日期到语言环境日期字符串:

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

    选项:

       DateFormat.getDateInstance() 
    

    -> 1969 年 12 月 31 日

       DateFormat.getDateTimeInstance() 
    

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

       DateFormat.getTimeInstance() 
    

    -> 下午 4:00:00

    【讨论】:

    • 如何从 DateFormat.getDateInstance() 中删除年份?
    【解决方案5】:

    这样就可以了:

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

    【讨论】:

    • 当用户在安卓设备中更改语言时,这会本地化吗?
    【解决方案6】:

    使用 SimpleDateFormat

    像这样:

    event.putExtra("starttime", "12/18/2012");
    
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    Date date = format.parse(bundle.getString("starttime"));
    

    【讨论】:

    • 是,使用 默认语言环境 以避免性能问题:new SimpleDateFormat("my-format", Locale.getDefault());
    【解决方案7】:

    关注这个:http://developer.android.com/reference/android/text/format/Time.html

    最好使用Android原生的Time类:

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

    然后格式化:

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

    【讨论】:

    【解决方案8】:

    这是最简单的方法:

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

    如果您正在寻找模式,请检查此 https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

    【讨论】:

      【解决方案9】:

      使用这两个作为类变量:

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

      并像这样使用它:

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

      【讨论】:

        【解决方案10】:

        日期时间格式说明

        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 )
        

        【讨论】:

        • 大写YYYY在某些情况下可能会被压扁,最好使用小写的
        【解决方案11】:

        这是我的方法,你可以定义输入输出格式。

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

        【讨论】:

          【解决方案12】:

          SimpleDateFormat

          我使用 SimpleDateFormat 无自定义模式设备预选格式从系统获取实际日期和时间:

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

          返回

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

          【讨论】:

            【解决方案13】:

            在 Time 类中使用构建!

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

            【讨论】:

            【解决方案14】:

            这段代码对我有用!

            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();
            

            【讨论】:

              【解决方案15】:

              最短路径:

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

              %tR%tH:%tM的缩写,&lt;表示重用最后一个参数(1$)。

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

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

              【讨论】:

              • 这肯定是最短的方法,尽管在不删除美元符号的情况下它在 Kotlin 上对我不起作用:String.format("%1tY-%&lt;tm-%&lt;td %&lt;tR", Calendar.getInstance())
              【解决方案16】:

              日期格式类使用作弊码生成日期。喜欢

              1. M -> 7, MM -> 07, MMM -> 七月, MMMM -> 七月
              2. EEE -> 周二,EEEE -> 周二
              3. z -> EST , zzz -> EST , zzzz -> 东部标准时间

              你可以查看更多秘籍here

              【讨论】:

                【解决方案17】:

                其他答案通常是正确的。我想贡献现代答案。大多数其他答案中使用的DateDateFormatSimpleDateFormat 类早已过时,多年来给许多程序员带来了麻烦。今天,我们在java.time,AKA JSR-310,现代 Java 日期和时间 API 方面有了更好的表现。你可以在Android上使用它吗?最肯定!在 ThreeTenABP 项目中,现代类已被反向移植到 Android。详情请见this question: How to use ThreeTenABP in Android Project

                这个 sn-p 应该让你开始:

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

                当我将计算机的首选语言设置为美国英语或英国英语时,会打印:

                Sep 28, 2017 10:45:00 PM
                

                当我将其设置为丹麦语时,我得到:

                28-09-2017 22:45:00
                

                所以它确实遵循配置。不过,我不确定它遵循您设备的日期和时间设置的具体细节,这可能因手机而异。

                【讨论】:

                  【解决方案18】:

                  此代码将返回当前日期和时间:

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

                  【讨论】:

                  • toLocaleString() 已弃用
                  【解决方案19】:

                  语言环境

                  要从毫秒获取区域设置格式的日期或时间,我使用了这个:

                  日期和时间

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

                  日期

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

                  时间

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

                  您可以使用其他日期样式和时间样式。有关样式的更多信息here

                  【讨论】:

                    【解决方案20】:

                    我是这样使用的:

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

                    【讨论】:

                      【解决方案21】:

                      试试:

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

                      当您访问传递的变量时:

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

                      【讨论】:

                        【解决方案22】:

                        避免 j.u.Date

                        Java(和 Android)中的 Java.util.Date 和 .Calendar 和 SimpleDateFormat 是出了名的麻烦。避开他们。它们非常糟糕,以至于 Sun/Oracle 放弃了它们,用 Java 8 中的新 java.time 包取代了它们(截至 2014 年在 Android 中没有)。新的java.time 的灵感来自Joda-Time 库。

                        乔达时间

                        Joda-Time 确实适用于 Android。

                        在 StackOverflow 中搜索“Joda”以找到许多示例和讨论。

                        使用 Joda-Time 2.4 的源代码花絮。

                        标准格式。

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

                        本地化格式。

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

                        【讨论】:

                          【解决方案23】:

                          回到2016年,当我想自定义格式(不是根据设备配置,如你所问...)我通常使用字符串资源文件:

                          在strings.xml中:

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

                          活动中:

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

                          这对于新的Date Binding Library 的发布也很有用。

                          所以我可以在布局文件中有这样的东西:

                          <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"
                              />
                          

                          在java类中:

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

                          【讨论】:

                            【解决方案24】:

                            android Time 类提供3种格式化方法http://developer.android.com/reference/android/text/format/Time.html

                            我就是这样做的:

                            /**
                            * 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;
                            }
                            

                            希望对你有帮助:-)

                            【讨论】:

                              【解决方案25】:

                              为时已晚,但可能对某人有所帮助

                              DateFormat.format(format, timeInMillis);
                              

                              这里format是你需要的格式

                              例如:“HH:mm”返回 15:30

                              【讨论】:

                                猜你喜欢
                                • 1970-01-01
                                • 1970-01-01
                                • 2018-05-20
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                • 1970-01-01
                                相关资源
                                最近更新 更多