Java的Date格式的應用__程式設計語言

來源:互聯網
上載者:User
/** * 從秒數獲得一個具體時間,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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.