Java Example – Converting a Timestamp to Time
The following example demonstrates how to use the format() method of the SimpleDateFormat class to convert a timestamp to time.
Date and time pattern (note that uppercase and lowercase have different meanings):
- yyyy: year
- MM: month
- dd: day
- hh: 1-12 hour format (1-12)
- HH: 24-hour format (0-23)
- mm: minute
- ss: second
- S: millisecond
- E: day of week
- D: day of year
- F: week of month (the total days elapsed in the month divided by 7)
- w: week of year
- W: week of month (calculated based on actual circumstances)
- a: AM/PM marker
- k: similar to HH, represents 24-hour format (1-24)
- K: similar to hh, represents 12-hour format (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
(
"
Formatting 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
(
"
Formatting result:
"
sd2
)
;
}
}
The output of the above code is:
格式化结果:2018-07-10 12:17:34
格式化结果:2018 年 07 月 10 日 12 时 17 分 34 秒
Java Examples