簡體   English   中英

Android 獲取當前時間戳?

[英]Android Get Current timestamp?

我想像這樣獲取當前時間戳: 1320917972

int time = (int) (System.currentTimeMillis());
Timestamp tsTemp = new Timestamp(time);
String ts =  tsTemp.toString();

解決辦法是:

Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();

來自開發者博客:

System.currentTimeMillis()是標准的“掛鍾”(時間和日期),表示自紀元以來的毫秒數。 掛鍾可以由用戶或電話網絡設置(請參閱setCurrentTimeMillis(long) ),因此時間可能會不可預測地向后或向前跳躍。 僅當與現實世界的日期和時間對應很重要時才應使用此時鍾,例如在日歷或鬧鍾應用程序中。 間隔或經過時間測量應使用不同的時鍾。 如果您正在使用System.currentTimeMillis() ,請考慮收聽ACTION_TIME_TICKACTION_TIME_CHANGEDACTION_TIMEZONE_CHANGED意圖廣播以了解時間何時更改。

1320917972是 Unix 時間戳,使用自 1970 年 1 月 1 日 00:00:00 UTC 以來的秒數。您可以使用TimeUnit類進行單位轉換 - 從System.currentTimeMillis()到秒。

String timeStamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));

您可以使用SimpleDateFormat類:

SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String format = s.format(new Date());

使用以下方法獲取當前時間戳。 這對我來說可以。

/**
 * 
 * @return yyyy-MM-dd HH:mm:ss formate date as string
 */
public static String getCurrentTimeStamp(){
    try {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDateTime = dateFormat.format(new Date()); // Find todays date

        return currentDateTime;
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }
}

它的使用很簡單:

long millis = new Date().getTime();

如果你想要它的特定格式,那么你需要像下面這樣的格式化程序

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String millisInString  = dateFormat.format(new Date());

這是一個人類可讀的時間戳,可以在文件名中使用,以防萬一有人需要我需要的東西:

package com.example.xyz;

import android.text.format.Time;

/**
 * Clock utility.
 */
public class Clock {

    /**
     * Get current time in human-readable form.
     * @return current time as a string.
     */
    public static String getNow() {
        Time now = new Time();
        now.setToNow();
        String sTime = now.format("%Y_%m_%d %T");
        return sTime;
    }
    /**
     * Get current time in human-readable form without spaces and special characters.
     * The returned value may be used to compose a file name.
     * @return current time as a string.
     */
    public static String getTimeStamp() {
        Time now = new Time();
        now.setToNow();
        String sTime = now.format("%Y_%m_%d_%H_%M_%S");
        return sTime;
    }

}

您可以通過嘗試以下代碼在 Android 中獲取當前時間戳

time.setText(String.valueOf(System.currentTimeMillis()));

和時間戳到時間格式

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(Long.parseLong(time.getText().toString())));
time.setText(dateString);

Kotlin 中的解決方案:

val nowInEpoch = Instant.now().epochSecond

確保您的最低 SDK 版本為 26。

這是最廣為人知的方法的比較列表在此處輸入圖片說明

時間

我想貢獻現代答案。

    String ts = String.valueOf(Instant.now().getEpochSecond());
    System.out.println(ts);

剛才運行時的輸出:

1543320466

雖然除以 1000 對許多人來說並不奇怪,但自己進行時間轉換可能很難快速閱讀,因此在可以避免的情況下進入是一個壞習慣。

我使用的Instant類是現代 Java 日期和時間 API java.time 的一部分。 它內置於新的 Android 版本、API 級別 26 及更高版本。 如果您正在為較舊的 Android 編程,您可能會得到向后移植,見下文。 如果您不想這樣做,可以理解,我仍然會使用內置轉換:

    String ts = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
    System.out.println(ts);

這與 Sealskej 的回答相同。 輸出和以前一樣。

問題:我可以在 Android 上使用 java.time 嗎?

是的,java.time 在較舊和較新的 Android 設備上都能很好地工作。 它只需要至少Java 6

  • 在 Java 8 及更高版本和更新的 Android 設備(從 API 級別 26)中,現代 API 是內置的。
  • 在非 Android Java 6 和 7 中獲得 ThreeTen Backport,新類的 backport(ThreeTen for JSR 310;請參閱底部的鏈接)。
  • 在(較舊的)Android 上使用 ThreeTen Backport 的 Android 版本。 它被稱為 ThreeTenABP。 並確保使用子包從org.threeten.bp導入日期和時間類。

鏈接

只需使用

long millis = new Date().getTime();

得到長毫秒的當前時間

這是另一個解決方案,在 kotlin 中:

val df: DateFormat = SimpleDateFormat("yyyy.MM.dd HH:mm:ss")
val timeStamp = df.format(Calendar.getInstance().time)

Output 示例:

“2022.04.22 10:22:35”

我建議使用 Hits 的答案,但添加語言環境格式,這是 Android 開發人員推薦的方式

try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return dateFormat.format(new Date()); // Find todays date
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

此代碼是 Kotlin 版本。 我有另一個想法在最后一位添加一個隨機洗牌整數來給出方差紀元時間。

科特林版

val randomVariance = (0..100).shuffled().first()
val currentEpoch = (System.currentTimeMilis()/1000) + randomVariance

val deltaEpoch = oldEpoch - currentEpoch

我認為使用這個 kode 會更好,然后依賴於 android 26 或更高版本

暫無
暫無

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

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