Strings are very easy to manipulate, and the String class itself provides many methods to play with data types and use them in different ways. We can convert Java date into String using the SimpleDateFormat class that provides many different formats. We can represent the date in various formats like mm-dd-yy or dd-mm-yyyy etc.
How to format Java date using SimpleDateFormat
We will first create a new Date() object, which gives us the current date and time. We will also get the current date and time from the Calendar instance and then convert it to the required formats using SimpleDateFormat class.
To get the date object, remember to import java.util.Date and not java.sql.Date.
In the main method, we will write the following:
Date today = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); String todaysDate = sdf.format(today); System.out.println(todaysDate);
If today is 22nd January of 2021, the program will output 22-01-2021.
Note that we use ‘MM’ for month, whereas the small m pair ‘mm’ is used for minutes. Let us see another format:
sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss"); todaysDate = sdf.format(today); System.out.println(todaysDate);
This will print: 22-Jan-2021 06:25:03
You can also change the symbols, for example, use ‘.’ instead of ‘-‘.
To get the dates for a particular timezone, use the TimeZone class.
We can get the today’s date also using Calendar instance as:
Date date = Calendar.getInstance().getTime(); System.out.println(new SimpleDateFormat("dd.MM.yyyy hh.mm.ss").format(date));
To get the day as well, we can use ‘EEE’:
sdf = new SimpleDateFormat("EEE, MMM dd, yyyy hh:mm:ss"); System.out.println(sdf.format(date));
This will print: Fri, Jan 22, 2021 06:56:31
You can use EEEE and MMMM to print the complete day and month name: Friday, January 22, 2021 06:59:26
We have seen how SimpleDateFormat can be used to format dates in various ways. We can also get individual parts. For example, if you want the day, you can simply construct an SDF object with “EEEE” and format the date to get just the day, for example, ‘Sunday’. There are many other methods in SimpleDateFormat, like getting the time zone from the Calendar instance of the SDF object, converting String to date, and so on. Check the Javadocs for more methods.
People are also reading: