Introduction
Java provides many methods to represent date and time. We use Date and Calendar to get the current date in Java. Parts of the date can be formatted using DateFormat or SimpleDateFormat for display. As of Java 8, to convert and get the current date (now) between different time zones, it is recommended to use ZonedDateTime; however same functionality can be achieved using Date and Calendar both as well.
Get the current date using java.util.Date
To get the current date, just create a new object of java.util.Date. Make sure you don’t import java.sql.Date.
To get the current date of a different timezone, you should set the timezone. If you don’t know the time zones, you can print the list and then select the one you want.
We import java.util.Calendar and then get the calendar instance.
Now use getTime() method to get the current date:
getTime() converts Calendar instance into Date object
To get the current date of a different time zone, use the same code as the Date object by passing the calDate instead of the dt object to the sdf object. System.out.println(sdf.format(calDate)); Here is the full example for your reference:
Conclusion
We have seen the usage of Date and Calendar to get the current date (now) or today’s date in Java. We have used a format that displays the day of the week, month in letters, date, time, time zone, and year. We can use any format using SimpleDateFormat , and the date & time will be displayed accordingly.
People are also reading:
Leave a Comment on this Post