Android获取当前时间戳?

我想获得当前的时间戳: 1320917972

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

解决scheme是:

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

从开发者博客:

System.currentTimeMillis()是从历元开始表示毫秒的标准“墙”时钟(时间和date)。 挂钟可以由用户或电话networking设置(参见setCurrentTimeMillis(long) ),所以时间可能会跳跃或转发不可预知的。 此时钟只能用于与真实世界date和时间的对应关系,例如在日历或闹钟应用程序中。 间隔或经过时间测量应使用不同的时钟。 如果您正在使用System.currentTimeMillis() ,请考虑监听ACTION_TIME_TICKACTION_TIME_CHANGEDACTION_TIMEZONE_CHANGED Intent广播以了解时间更改的时间。

您可以使用SimpleDateFormat类:

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

这里有一个人类可读的时间戳,可以用在一个文件名,以防万一有人需要我需要的相同的东西:

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

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

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

这很简单:

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

如果你想特殊的格式,那么你需要像下面的Formatter

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

我build议使用Hits的答案,但添加一个区域设置格式,这是Android开发人员推荐的方式 :

 try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); return dateFormat.format(new Date()); // Find todays date } catch (Exception e) { e.printStackTrace(); return null; }