/**
* 从秒数获得一个具体时间,24小时制,比如2016-12-12 23:23:15
* @param second
* @return
*/
public static String second2Moment24(long second){
Date date = new Date(second*1000);
SimpleDateFormat ft =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ft.setTimeZone(TimeZone.getTimeZone("GMT+8"));
return ft.format(date);
}
/**
* 从秒数获得一个具体时间,12小时制,比如2016-12-12 23:23:15
* @param second
* @return
*/
public static String second2Moment12(long second){
Date date = new Date(second*1000);
SimpleDateFormat ft =
new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
ft.setTimeZone(TimeZone.getTimeZone("GMT+8"));
return ft.format(date);
}
/**
* 从秒数获得一个具体时间,24小时制,比如2016-12-12 23:23:15
* @param second
* @return
*/
public static String second2MomentGMT0(long second){
Date date = new Date(second*1000);
SimpleDateFormat ft =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ft.setTimeZone(TimeZone.getTimeZone("GMT+0"));
return ft.format(date);
}
/**
* 从一个具体时间,比如2016-12-12 23:23:15,获得秒数
* @param time
* @return
*/
public static long getTimeStamp(String time)
{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8"));
Date date = null;
try
{
date = simpleDateFormat.parse(time);
} catch (ParseException e)
{
return 0;
}
long timeStemp = date.getTime() / 1000;
return timeStemp;
}
1、为什么从System.currentTimeMillis()转成标准时间格式会相差12个小时?
比如当前时间为2016-12-19 21:36:20,调用second2Moment12(System.currentTimeMillis()/1000),输出的是2016-12-19 09:36:20.
原因是弄混了12小时制和24小时制,SimpleDateFormat应该使用"
yyyy-MM-dd HH:mm:ss"
2、为什么从System.currentTimeMillis()转成标准时间格式会相差8个小时?
比如当前时间为2016-12-19 21:36:20,调用second2MomentGMT0(System.currentTimeMillis()/1000),输出的是2016-12-19 13:36:20.
用System.currentTimeMillis()获取系统时间是国际标准的时间,是0时区的时间。原因有可能是SimpleDateFormat没有设置时区,ft.setTimeZone(
TimeZone.getTimeZone("GMT+8"))。
3、如何从一个时间字符串比如2016-12-19 13:36:20获得其秒数,可以用来比较时间的早晚
比如当前时间为2016-12-19 21:36:20,调用getTimeStamp("2016-12-19 21:36:20"),输出的是1482154580.