Display Current Date in Java SimpleDateFormat: Parse and Format Dates Compare Dates Example
Let us first understand the parameters that consist of a Date.
It will primarily contain –
The year (in either 2 or 4 digits) The month (in either 2 digits, First 3 letters of the month or the entire word of the month). The date (it will be the actual date of the month). The day (the day at the given date – like Sun, Mon, Tue, etc.)
Concerning computer systems, there are quite a lot of parameters that can be used to associate with a date. We shall see them in the later parts of this topic.
Display Date in Java
Now let us see how Java provide us the Date. First, we shall see how to get the current date- Java provides a Date class under the java.util package, The package provides several methods to play around with the date. You can use the Date object by invoking the constructor of Date class as follows: Output: In above example date shown in default format, If we want to show the date and time in another format, first understand the Formatting of date.
SimpleDateFormat: Parse and Format Dates
You all must have learned the alphabets in your kindergarten …. Let us now learn the ABC’s of the date format. Don’t worry, you don’t need to remember all of these, they can be referred anytime you need to format a particular date.
How to use the SimpleDateFormat?
Java provides a class called a SimpleDateFormat that allows you to format and parse dates in the as per your requirements. You can use the above characters to specify the format- For example:
- Date format required: 2012.10.23 20:20:45 PST The appropriate date format specified will be- yyyy.MM.dd HH:mm:ss zzz
- Date format required:09:30:00 AM 23-May-2012 The appropriate date format specified will be-hh:mm:ss a dd-MMM-yyyy Tip: Be careful with the letter capitalization. If you mistake M with m, you will undesired results! Let’s learn this with a code example. Output:
Compare Dates Example
The most useful method of comparing dates is by using the method – compareTo() Let us take a look at the below code snippet- Output: