Learn to create new date, get current date, parse date to string or format Date
object using java.util.Date class. These usecases are frequently required, and having them in one place will help in saving time for many of us.
It is worth noting that there is no timezone information associated with Date instance. A Date instance represents the time spent since Epach in milliseconds. If we print the date instance, it always prints the default or local timezone of the machine. So the timezone information printed in Date.toString() method should not misguide you.
1. Formatting a Date to String
Java program of formatting Date to string using SimpleDateFormat.format()
. Please note that SimpleDateFormat is not a thread-safe class, so we should not share its instance with multiple threads.
Refer SimpleDateFormat JavaDoc for detailed date and time patterns. Below is a list of the most common pattern letters you can use.
Pattern | Example |
---|---|
yyyy-MM-dd (ISO) | “2018-07-14” |
dd-MMM-yyyy | “14-Jul-2018” |
dd/MM/yyyy | “14/07/2018” |
E, MMM dd yyyy | “Sat, Jul 14 2018” |
h:mm a | “12:08 PM” |
EEEE, MMM dd, yyyy HH:mm:ss a | “Saturday, Jul 14, 2018 14:31:06 PM” |
yyyy-MM-dd'T'HH:mm:ssZ | “2018-07-14T14:31:30+0530” |
hh 'o''clock' a, zzzz | “12 o’clock PM, Pacific Daylight Time” |
K:mm a, z | “0:08 PM, PDT” |
2. Parsing a String to Date
Java program of parsing a string to Date instance using SimpleDateFormat.parse() method.
3. Getting Current Date and Time
java.util.Date
class represents the date and time elapsed since the epoch. Given below are the Java programs for getting the current date and time and printing in a given format.
For reference, since Java 8, we can use LocalDate
, LocalTime
and LocalDateTime
classes.
4. Convert between Date and Calendar
4.1. Converting Calendar to Date
4.2. Converting Date to Calendar
5. Comparing Two Dates
We can compare two two date instances using its compareTo() method. It returns an integer value representing given date is before or after another date.
The comparison date1.CompareTo(date2)
will return:
- a value 0 if date2 is equal to date1;
- a value less than 0 if date1 is before date2;
- a value greater than 0 if date1 is after date2.
6. Extracting Days, Months and Years
Java program to get date parts such as year, month, etc separately.
The methods to get the year, month, day of the month, hour, etc. are deprecated. If you need to get or set the year, month, day of the month, etc. use a java.util.Calendar
instead.
Happy Learning !!
Comments