我想要得到当前的时间戳:1320917972
int time = (int) (System.currentTimeMillis());
Timestamp tsTemp = new Timestamp(time);
String ts = tsTemp.toString();
我想要得到当前的时间戳:1320917972
int time = (int) (System.currentTimeMillis());
Timestamp tsTemp = new Timestamp(time);
String ts = tsTemp.toString();
当前回答
Kotlin解决方案:
val nowInEpoch = Instant.now().epochSecond
确保你的最低SDK版本是26。
其他回答
这是一个人类可读的时间戳,可以用在文件名中, 以防有人需要和我一样的东西:
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 tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
这里是另一个解决方案,这是在kotlin:
val df: DateFormat = SimpleDateFormat("yyyy.MM.dd HH:mm:ss")
val timeStamp = df.format(Calendar.getInstance().time)
输出的例子:
"2022.04.22 10:22:35"
这里是最广为人知的方法的比较列表
我建议使用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;
}