天天看點

Android 擷取時間戳 和時間戳轉日期

 擷取系統時間戳

public String getTime(){
    long time=System.currentTimeMillis()/1000;//擷取系統時間的10位的時間戳
    String  str=String.valueOf(time);
    return str;
}      

、擷取系統時間

long currentTime = System.currentTimeMillis();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年-MM月dd日-HH時mm分ss秒");
Date date = new Date(currentTime);
System.out.println(formatter.format(date));      

結果如下

2017年-05月26日-14時49分29秒

時間戳轉換日期

public static String timetodate(String time) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(Long.valueOf(time));
    SimpleDateFormat sf = new SimpleDateFormat("MM-dd ");//這裡的格式可換"yyyy年-MM月dd日-HH時mm分ss秒"等等格式

    String date = sf.format(calendar.getTime());
    return date;

}      
/*
   * 将時間轉換為時間戳
   */
public static String dateToStamp(String s) throws ParseException {
    String res;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = simpleDateFormat.parse(s);
    long ts = date.getTime();
    res = String.valueOf(ts);
    return res;
}