我想要得到当前的时间戳: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();
当前回答
你可以通过尝试下面的代码在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 df: DateFormat = SimpleDateFormat("yyyy.MM.dd HH:mm:ss")
val timeStamp = df.format(Calendar.getInstance().time)
输出的例子:
"2022.04.22 10:22:35"
来自开发者博客:
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.
解决方案是:
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
此代码是Kotlin版本。我有另一个想法,添加一个随机洗牌整数在最后一位给出方差纪元时间。
芬兰湾的科特林版本
val randomVariance = (0..100).shuffled().first()
val currentEpoch = (System.currentTimeMilis()/1000) + randomVariance
val deltaEpoch = oldEpoch - currentEpoch
我认为使用这个代码会更好,然后依赖于android版本26或更高
它的用法很简单:
long millis = new Date().getTime();
如果你想在特定的格式,那么你需要像下面这样的Formatter
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String millisInString = dateFormat.format(new Date());