簡體   English   中英

Android:如何正確格式化日期和時間字符串?

[英]Android: How to Format Date and Time Strings correctly?

我應該如何正確格式化 Android 平台的日期時間字符串?

這是一些代碼:

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

您可以采用多種方式格式化它...

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

在這里您可以輸入其他格式,例如

K:毫米

H:毫米

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

檢查一下。... http : //developer.android.com/reference/java/text/SimpleDateFormat.html

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

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年1月19日UTC 1970-01-01T00:00:00Z的紀元參考以來的毫秒數。

long millisSinceEpoch = file.lastModified() ;

將該數字解析為現代的java.time對象。

Instant instant = Instant.ofEpochMilli( millisSinceEpoch ) ;

使用標准ISO 8601格式生成一個String來表示該值。

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

狂歡節2018年6月17日à10:40:39


關於java.time

java.time框架內置於Java 8及更高版本中。 這些類取代了麻煩的舊的舊式日期時間類,例如java.util.DateCalendarSimpleDateFormat

現在處於維護模式Joda-Time項目建議遷移到java.time類。

要了解更多信息,請參見Oracle教程 並在Stack Overflow中搜索許多示例和說明。 規格為JSR 310

您可以直接與數據庫交換java.time對象。 使用與JDBC 4.2或更高版本兼容的JDBC驅動程序 不需要字符串,不需要java.sql.*類。

在哪里獲取java.time類?

ThreeTen-Extra項目使用其他類擴展了java.time。 該項目為將來可能在java.time中添加內容提供了一個試驗場。 您可以在這里找到一些有用的類,比如IntervalYearWeekYearQuarter ,和更多

更新:現在處於維護模式Joda-Time項目建議遷移到java.time類。

喬達時間

安裝第三方庫Joda-Time

默認情況下,Joda-Time以ISO 8601格式輸出字符串。 全世界幾乎任何人都可以直觀地理解該格式。

在StackOverflow.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

我想在這里添加我的份額。

注意,用戶可以在設置中設置他的首選格式。 有關如何檢索的示例:

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 + ".";
}

雖然,這個問題已經很老了,但它可能會對想要這個答案的 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) {
        ""
    }
}

現在在您的活動/功能/數據源映射器中使用此方法以字符串格式獲取日期,如下所示

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

輸出將是這樣的

18-01-2022

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM