我想要得到当前的时间戳: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();
当前回答
解决方案是:
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
其他回答
Kotlin解决方案:
val nowInEpoch = Instant.now().epochSecond
确保你的最低SDK版本是26。
来自开发者博客:
System.currentTimeMillis() is the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis(), consider listening to the ACTION_TIME_TICK, ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes.
这里是最广为人知的方法的比较列表
这是一个人类可读的时间戳,可以用在文件名中, 以防有人需要和我一样的东西:
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;
}
}
java.time
我愿意给出现代的答案。
String ts = String.valueOf(Instant.now().getEpochSecond());
System.out.println(ts);
刚才运行时输出:
1543320466
虽然除以1000对许多人来说并不奇怪,但自己做时间转换可能很难快速读取,所以当你可以避免它时,这是一个坏习惯。
我正在使用的Instant类是java的一部分。时间,现代Java日期和时间API。它是内置在新的Android版本,API级别26及以上。如果你正在为旧的Android编程,你可能会得到后端口,见下文。如果你不想这样做,可以理解,我仍然使用内置转换:
String ts = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
System.out.println(ts);
这与sealskej的答案相同。输出与之前相同。
问:我可以使用java吗?Android的时间?
是的,java。time在新旧安卓设备上都能很好地运行。它只需要至少Java 6。
在Java 8及以后版本和更新的Android设备上(从API级别26开始),内置了现代API。 在非android Java 6和7中获得ThreeTen Backport,新类的后端口(JSR 310的ThreeTen;参见底部的链接)。 在(旧的)Android上使用ThreeTen Backport的Android版本。叫做ThreeTenABP。并确保从org.three .bp导入带有子包的日期和时间类。
链接
Oracle教程:Date Time解释如何使用java.time。 Java规范请求(JSR) 310,其中Java。时间是最早被描述的。 ThreeTen Backport项目,java的Backport。Java 6和7的时间(JSR-310的ThreeTen)。 ThreeTenABP, Android版的ThreeTen Backport 问:如何在Android项目中使用ThreeTenABP,并有一个非常详细的解释。