安卓如何获取当前时间戳?

299

我想要获取当前时间戳,像这样:1320917972

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

2
FYI,像java.util.Datejava.util.CalendarTimestamp这样的老旧日期时间类现在已经被废弃,由java.time类所代替。大多数java.time的功能已经被移植到Java 6和Java 7中,它们包含在ThreeTen-Backport项目中。该项目还进一步适配了早期的Android版本,形成ThreeTenABP项目。请参阅如何使用ThreeTenABP… - Basil Bourque
14个回答

356

解决方案是:

Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();

1
这并没有考虑设备的时区偏移量。 - kjdion84
3
请问,你为什么觉得这很重要?仅仅基于这个问题吗? - Cԃաԃ
有没有办法将这个转换为 int 类型? - Donald Duck

89

来自开发者博客:

System.currentTimeMillis() 是标准的“墙上”时钟(时间和日期),表示自纪元以来的毫秒数。墙上时钟可以被用户或手机网络设置(参见 setCurrentTimeMillis(long)),因此时间可能会不可预测地向前或向后跳跃。只有在与真实世界的日期和时间对应重要的情况下,例如在日历或闹钟应用中,才应使用此时钟。间隔或经过时间测量应使用另一个时钟。如果您正在使用 System.currentTimeMillis(),请考虑侦听 ACTION_TIME_TICKACTION_TIME_CHANGEDACTION_TIMEZONE_CHANGED 意图广播,以了解时间何时更改。


12
从http://developer.android.com/reference/java/lang/System.html#nanoTime%28%29中,我发现`System.nanoTime()`是`System.currentTimeMillis()`的替代品,它没有不可预测的波动,并且专门用于测量持续时间差异。 - Bianca Daniciuc
2
@ana01 "零值通常是设备上次启动时" - 因此仅在比较同一设备上的持续时间差异时才可以使用。例如,不适用于数据库存储。 - Michał Klimczak
1
只是一个注释,针对@ana01的评论,指出System.nanoTime()不适合用于显示墙上时钟时间。为此,请使用System.currentTimeMillis() - Akash Agarwal

40

1320917972 是自1970年1月1日00:00:00 UTC以来所用秒数的Unix时间戳。您可以使用TimeUnit类进行单位转换 - 从System.currentTimeMillis()转换为秒。

String timeStamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));

33
您可以使用SimpleDateFormat类:
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String format = s.format(new Date());

30
不是时间戳(自纪元以来的时间)。 - Michał Klimczak
2
不要使用这种方法,它不仅效率低下(需要创建SimpleDateFormat、日期对象和转换),而且还存在其他问题。请避免使用。 - Seynorth
1
你回答了其他问题,但也是有效的。 - ersks

24

使用以下方法获取当前时间戳,这个方法对我来说很有效。

/**
 * 
 * @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;
    }
}

40
那不是时间戳。 - user1318194
1
@Hits,这是Simple Date Format,而不是时间戳。你只是将变量名命名为currentTimeStap。 - ersks

13

使用方法简单:

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

如果您想要特定格式,则需要像下面这样的格式化程序。

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

1
这会给出GMT时间。 - nyxee

9
以下是最广为人知的方法的比较列表: enter image description here

9
你可以尝试以下代码在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);

8

Kotlin实现方案:

val nowInEpoch = Instant.now().epochSecond

请确保您的最小SDK版本为26。


8

这是一个易于阅读的时间戳,可以用于文件名,以防有人需要我所需的相同内容:

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

}

1
嗨,您能告诉我如何对时间戳列表进行最佳排序吗?我本来打算自己排序,但是想了想可能会有更好的方法。 - Abbas
请注意,对于任何阅读此内容的人来说,"android.text.format.Time"现已被弃用,以备将来参考。 - jason.kaisersmith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接