Java Examples - Convert Timestamp to Time
The following example demonstrates how to use the format() method of the SimpleDateFormat class to convert a timestamp into time.
Date and time patterns (note the case; different cases have different meanings):
- yyyy: year
- MM: month
- dd: day
- hh: 1~12 hour system (1-12)
- HH: 24-hour system (0-23)
- mm: minute
- ss: second
- S: millisecond
- E: day of the week
- D: day of the year
- F: week of the month (divides the total number of days passed in this month by 7)
- w: week of the year
- W: week of the month (calculated based on actual circumstances)
- a: AM/PM marker
- k: similar to HH, represents the 24-hour system of a day (1-24)
- K: similar to hh, represents the 12-hour system of a day (0-11)
- z: represents the time zone
Main.java file
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main{
public static void main(String[] args){
Long timeStamp = System.currentTimeMillis(); //Get the current timestamp
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp)))); //Convert timestamp to time
System.out.println("Formatted result:" + sd);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy year MM month dd day HH hour mm minute ss second");
String sd2 = sdf2.format(new Date(Long.parseLong(String.valueOf(timeStamp))));
System.out.println("Formatted result:" + sd2);
}
}
The output of the above code is:
格式化结果:2018-07-10 12:17:34 格式化结果:2018 年 07 月 10 日 12 时 17 分 34 秒Other Extensions
Java Examples