【问题标题】:Android: How to Format Date and Time Strings correctly?Android:如何正确格式化日期和时间字符串?
【发布时间】:2026-01-21 19:55:02
【问题描述】:

我应该如何正确格式化 Android 平台的 DateTime 字符串?

下面是一些代码:

String path = getFilesDir().getPath();
String filePath = path + "/somefile.xml";
File file = new File(filePath);
Date lastModDate = new Date(file.lastModified());
String filelastModDate = "Updated: " + lastModDate.toString();

【问题讨论】:

  • 究竟是为了什么?一些系统库可以阅读?展示给人类?
  • 使用SimpleDateFormat。如果您有问题,请提出更具体的问题。
  • 仅供参考,java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 等麻烦的旧日期时间类现在已被 java.time 类所取代。在ThreeTen-Backport 项目中,大部分java.time 功能都被反向移植到Java 6 和Java 7。在ThreeTenABP 项目中进一步适用于早期的Android。见How to use ThreeTenABP…

标签: java android date time format


【解决方案1】:

你可以用各种方式格式化它...

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
String currentTime = sdf.format(date);

这里可以放其他格式

k:mm

h:mm

h:mm dd/MM/yyyy
等等……

检查这个....http://developer.android.com/reference/java/text/SimpleDateFormat.html

【讨论】:

  • 感谢@receme 我使用了:SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy 'at' HH:mm:ss", Locale.getDefault());
  • 仅供参考,java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 等麻烦的旧日期时间类现在已被 java.time 类所取代。许多 java.time 功能在ThreeTen-Backport 项目中被反向移植到Java 6 和Java 7。在ThreeTenABP 项目中进一步适用于早期的Android。见How to use ThreeTenABP…
【解决方案2】:

谢谢@receme 我解决了。像这样:

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a",Locale.getDefault());
String currentTime = sdf.format(date);
Log.i(LOGTAG,"Current Time: " + currentTime);

【讨论】:

    【解决方案3】:

    tl;博士

    Instant.ofEpochMilli(    // Parse milliseconds count to a moment in UTC.
        file.lastModified()  // A count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z.
    )                        // Returns a `Instant` object.
    .atZone(                 // Adjust from UTC to some time zone. Same moment, same point on the timeline, different wall-clock time.
        ZoneId.of( "Africa/Tunis" )
    )                        // Returns a `ZonedDateTime` object.
    .format(                 // Generate a `String`.
        DateTimeFormatter
        .ofLocalizedDateTime( FormatStyle.FULL )  // Specify how long or abbreviated.
        .withLocale( Locale.JAPAN )  // Specify a `Local` to determine human language and cultural norms used in localizing.
    )                        // Returns a `String`. 
    

    java.time

    现代方法使用 java.time 类。

    File.lastModified 方法返回自 1970 年第一刻(UTC,1970-01-01T00:00:00Z)的纪元参考以来的毫秒数。

    long millisSinceEpoch = file.lastModified() ;
    

    将该数字解析为现代 java.time 对象。

    Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ;
    

    生成一个String 以使用标准 ISO 8601 格式表示该值。

    String output = instant.toString() ;  // Generate a `String` in standard ISO 8601 format.
    

    2018-07-16T22:40:39.937Z

    要通过特定地区(时区)的人们使用的挂钟时间的镜头查看同一时刻,请申请ZoneId 以获取ZonedDateTime

    ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
    ZonedDateTime zdt = instant.atZone( z ) ;
    

    2018-07-17T10:40:39.937+12:00[太平洋/奥克兰]

    java.time自动本地化。要进行本地化,请指定:

    • FormatStyle 确定字符串的长度或缩写。
    • Locale 确定:
      • 人类语言用于翻译日名、月名等。
      • 文化规范决定缩写、大写、标点、分隔符等问题。

    例子:

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

    mardi 17 juillet 2018 à 10:40:39 heure normale de la Nouvelle-Zélande


    关于java.time

    java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

    Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

    要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

    您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。

    从哪里获得 java.time 类?

    ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

    【讨论】:

      【解决方案4】:

      我想在这里添加我的分享。

      请注意,用户可以在设置中设置自己喜欢的格式。检索方式示例:

      static DateFormat getUserDateFormat(Context context) {
          if (mUserDateFormat == null)
              mUserDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
          return mUserDateFormat;
      }
      

      另见...getTimeFormat

      然后你就有了一个 java DateFormat 用于上面提到的例子。

      此外,Android 包含它自己的 TextFormat 类,请看这里:http://developer.android.com/reference/android/text/format/package-summary.html

      这可能看起来像:

      static String getAppExpiredString() {
          String date = android.text.format.DateFormat.getDateFormat(getAppContext()).format(App_Main.APP_RUN_TILL.getTime());
          return getAppContext().getString(R.string.app_expired) + " " + date + ".";
      }
      

      【讨论】:

        【解决方案5】:

        更新:Joda-Time 项目现在位于 maintenance mode,建议迁移到 java.time 类。

        乔达时间

        安装第三方库,Joda-Time

        默认情况下,Joda-Time 以ISO 8601 格式输出字符串。全世界几乎任何人都可以直观地理解这种格式。

        在 *.com 上搜索更多示例。

        // © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
        // import org.joda.time.*;
        
        DateTime now = new DateTime();
        System.out.println( now );
        

        运行时……

        2013-12-05T19:55:43.897-08:00
        

        【讨论】:

          【解决方案6】:

          虽然,这个问题已经很老了,但它可能会对想要这个答案的 Kotlin 版本的人有所帮助。这里我取一个空文件名 DateUtil 并创建一个名为 getDateString() 的函数,它有 3 个参数。

          1st argument : Your input date
          2nd argument : Your input date pattern
          3rd argument : Your wanted date pattern
          

          DateUtil.kt

          object DatePattern {
              const val YEAR_MONTH_DAY = "yyyy-MM-dd"
              const val DAY_MONTH_YEAR = "dd-MM-yyyy"
              const val RFC3339 = "yyyy-MM-dd'T'HH:mm:ss'Z'"
          }
          
          fun getDateString(date: String, inputDatePattern: String, outputDatePattern: String): String {
              return try {
                  val inputFormat = SimpleDateFormat(inputDatePattern, getDefault())
                  val outputFormat = SimpleDateFormat(outputDatePattern, getDefault())
          
                  outputFormat.format(inputFormat.parse(date))
              } catch (e: Exception) {
                  ""
              }
          }
          

          现在在您的活动/功能/dataSourse Mapper 中使用此方法以字符串格式获取日期,如下所示

          getDate("2022-01-18T14:41:52Z", RFC3339, DAY_MONTH_YEAR)
          

          输出会是这样的

          18-01-2022
          

          【讨论】:

            最近更新 更多