Java examples for Date Time:Date Time Format
Format date and time with DateTimeFormatter
import java.time.DateTimeException; import java.time.LocalDateTime; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class Main { public static void main(String[] args) { try {/*from w w w . ja v a 2 s . c o m*/ DateTimeFormatter dateFormatter = DateTimeFormatter .ofPattern("MMMM dd yyyy"); LocalDateTime now = LocalDateTime.now(); String output = now.format(dateFormatter); System.out.println(output); DateTimeFormatter dateFormatter2 = DateTimeFormatter .ofPattern("MM/dd/YY HH:mm:ss"); String output2 = now.format(dateFormatter2); System.out.println(output2); DateTimeFormatter dateFormatter3 = DateTimeFormatter .ofPattern("hh 'o''clock' a, zzzz"); ZonedDateTime zdt = ZonedDateTime.now(); String output3 = zdt.format(dateFormatter3); System.out.println(output3); } catch (DateTimeException ex) { System.out.println("Cannot be formatted: " + ex); } } }
Pattern Characters
Character | Description |
---|---|
G | Era |
y | Year |
Y | Week year |
M | Month in year |
w | Week in year |
W | Week in month |
D | Day in year |
d | Day in month |
F | Day of week in month |
E | Name of day in week |
u | Number of day in week |
a | AM/PM |
H | Hour in day (0-23) |
k | Hour in day (1-24) |
K | Hour in AM/PM (0-11) |
h | Hour in AM/PM (1-12) |
m | Minute in hour |
s | Second in minute |
S | Millisecond |
z | General time zone |
Z | RFC 822 time zone |
X | ISO 8601 time zone |