Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Example – Converting a Timestamp to Time

Java Example – Converting a Timestamp to Time

Java Examples Java Examples

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):

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 Java Examples