我想要得到当前的时间戳: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);

其他回答

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

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

解决方案是:

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

它的用法很简单:

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

如果你想在特定的格式,那么你需要像下面这样的Formatter

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

这是一个人类可读的时间戳,可以用在文件名中, 以防有人需要和我一样的东西:

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

}

你可以使用SimpleDateFormat类:

SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String format = s.format(new Date());