我想要获取当前时间戳,像这样:1320917972
int time = (int) (System.currentTimeMillis());
Timestamp tsTemp = new Timestamp(time);
String ts = tsTemp.toString();
解决方案是:
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
int
类型? - Donald Duck来自开发者博客:
System.currentTimeMillis()
是标准的“墙上”时钟(时间和日期),表示自纪元以来的毫秒数。墙上时钟可以被用户或手机网络设置(参见 setCurrentTimeMillis(long)),因此时间可能会不可预测地向前或向后跳跃。只有在与真实世界的日期和时间对应重要的情况下,例如在日历或闹钟应用中,才应使用此时钟。间隔或经过时间测量应使用另一个时钟。如果您正在使用 System.currentTimeMillis()
,请考虑侦听 ACTION_TIME_TICK
、ACTION_TIME_CHANGED
和 ACTION_TIMEZONE_CHANGED
意图广播,以了解时间何时更改。
System.nanoTime()
不适合用于显示墙上时钟时间。为此,请使用System.currentTimeMillis()
。 - Akash Agarwal1320917972 是自1970年1月1日00:00:00 UTC以来所用秒数的Unix时间戳。您可以使用TimeUnit
类进行单位转换 - 从System.currentTimeMillis()
转换为秒。
String timeStamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
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());
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。
这是一个易于阅读的时间戳,可以用于文件名,以防有人需要我所需的相同内容:
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.util.Date
、java.util.Calendar
和Timestamp
这样的老旧日期时间类现在已经被废弃,由java.time类所代替。大多数java.time的功能已经被移植到Java 6和Java 7中,它们包含在ThreeTen-Backport项目中。该项目还进一步适配了早期的Android版本,形成ThreeTenABP项目。请参阅如何使用ThreeTenABP…。 - Basil Bourque