Java Example – Getting the Current Time
The following example demonstrates how to use the Date class and the format(date) method of the SimpleDateFormat class to output the current time:
Main.java File
import
java
.
text
.
SimpleDateFormat
;
import
java
.
util
.
Date
;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
)
;
//
Formatted time
sdf
.
applyPattern
(
"
yyyy-MM-dd HH:mm:ss a
"
)
;
//
a is the AM/PM marker
Date
date
=
new
Date
(
)
;
//
Get the current time
System
.
out
.
println
(
"
Current time:
"
sdf
.
format
(
date
)
)
;
//
Output the formatted current time (24-hour format)
}
}
The output of the above code is:
现在时间:2015-03-27 21:27:28 下午
Java Examples