How to get date and time in Java
calendar
date
format date
java
In Java, when it about the date, time and formatting date is mostly about three classes: Date, Calendar, and SimpleDateFormat.
Using Date
To create a Date object containing the current data:
Date date = new Date();
Using Calendar
To create a Date object containing the current date using Calendar class:
Calendar calendar = Calendar.getInstance();
Date date2 = calendar.getTime();
Formatter
To format the date in different formats SimpleDateFormat can be used.
String FORMAT = "yyyy-MM-dd HH:mm:ss";
DateFormat formater = new SimpleDateFormat(FORMAT);
Here are some formats examples.
Date and Time Pattern | Result |
---|---|
"yyyy.MM.dd G 'at' HH:mm:ss z" |
2001.07.04 AD at 12:08:56 PDT |
"EEE, MMM d, ''yy" |
Wed, Jul 4, '01 |
"h:mm a" |
12:08 PM |
"hh 'o''clock' a, zzzz" |
12 o'clock PM, Pacific Daylight Time |
"K:mm a, z" |
0:08 PM, PDT |
"yyyyy.MMMMM.dd GGG hh:mm aaa" |
02001.July.04 AD 12:08 PM |
"EEE, d MMM yyyy HH:mm:ss Z" |
Wed, 4 Jul 2001 12:08:56 -0700 |
"yyMMddHHmmssZ" |
010704120856-0700 |
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" |
2001-07-04T12:08:56.235-0700 |
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" |
2001-07-04T12:08:56.235-07:00 |
"YYYY-'W'ww-u" |
2001-W27-3 |
Example
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateTests {
public static void main(String[] args) {
String FORMAT = "yyyy-MM-dd HH:mm:ss";
DateFormat formater = new SimpleDateFormat(FORMAT);
System.out.println("Date Formater Example");
System.out.println();
Date date1 = new Date();
System.out.println("Using Date: " + formater.format(date1));
System.out.println();
Calendar calendar = Calendar.getInstance();
Date date2 = calendar.getTime();
System.out.println("Using Calendar: " +formater.format(date2));
}
}
Output
Date Formater Example
Using Date: 2016-05-05 16:02:13
Using Calendar: 2016-05-05 16:02:13