Java如何把UNIX時間戳轉換成日期格式-日期格式轉化時間戳戳-當前時間戳
阿新 • • 發佈:2019-01-02
開發中,經常需要把UNIX時間戳通過日期格式顯示出來,如下可以輸出日期格式
package com.self.date; import java.util.Date; import java.text.SimpleDateFormat; import java.text.ParseException; public class DateTest{ public static final String GSTIME="yyyy-MM-dd HH:mm:ss"; //UNIX時間戳轉換日期:方法一 //方法一,可能會報Long未定義錯誤;[未知,若有知道的,請留下言] //當然可以轉換成 str=unix_time.format(new Date(Long.parseLong(nowtime+"000"))); public static String getTimestampDate(String timestamp){ String str; SimpleDateFormat unix_time=new SimpleDateFormat(GSTIME); str=unix_time.format(new Date(Long.valueOf(timestamp+"000"))); //此處增加"000"是因為Date類中,傳入的時間單位為毫秒。 return str; } //時間戳轉換成日期格式:方法二 public static void getUnixTransferTime(){ System.out.println("轉換的日期是:"); long nowtime=1541261100;//某個時間戳; Date date=new Date(nowtime*1000); SimpleDateFormat format=new SimpleDateFormat(GSTIME); String nowDateString=format.format(date); System.out.println(nowDateString); } //日期格式轉換為UNIX時間戳 public static String getDateTimestamp(String timestamp) throws ParseException{ String str; SimpleDateformat date_time=new SimpleDateFormat(GSTIME); Date date=date_time.parse(timestamp); long ts=date.getTime(); str=String.valueOf(ts/1000); return str; } //獲取當前時間時間戳 public static String timecurrentTime(){ long time=System.currentTimeMillis(); String str=String.valueOf(time/1000); return str; } }