/** * 從秒數獲得一個具體時間,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.