我想要得到当前的时间戳:1320917972

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

当前回答

我建议使用Hits的答案,但添加一个Locale格式,这是如何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

我认为使用这个代码会更好,然后依赖于android版本26或更高

你可以使用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;
    }
}

这是一个人类可读的时间戳,可以用在文件名中, 以防有人需要和我一样的东西:

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

}

它的用法很简单:

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

如果你想在特定的格式,那么你需要像下面这样的Formatter

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