Get Current Date in Java
Here is the simple program showing how we can use these classes to get the current date and time in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.journaldev.util; import java.util.Calendar; import java.util.Date; public class DateAndTimeUtil { public static void main(String[] args) { //Get current date using Date Date date = new Date(); System.out.println("Current date using Date = "+date.toString()); //Get current date using Calendar Calendar cal = Calendar.getInstance(); System.out.println("Current date using Calendar = "+cal.getTime()); //Get current time in milliseconds System.out.println("Current time in milliseconds using Date = "+date.getTime()); System.out.println("Current time in milliseconds using Calendar = "+cal.getTimeInMillis()); } } |
Output of the above program is:
1 2 3 4 5 6 |
<span style="color: #008000;"><strong><code> Current date using Date = Thu Nov 15 13:51:03 PST 2012 Current date using Calendar = Thu Nov 15 13:51:03 PST 2012 Current time in milliseconds using Date = 1353016263692 Current time in milliseconds using Calendar = 1353016263711 </code></strong></span> |
Few points to note while getting the current date in java:
- Calendar.getInstance() is more expensive method, so use it only when you need Calendar object. Else use Date object.
- The number of milliseconds is the number of milliseconds since January 1, 1970, 00:00:00 GMT.
- Notice the difference between milliseconds in Calendar and Date object, it’s because of the time taken for java program to create Date and Calendar object. Date object is created first, hence it’s milliseconds value is lower.
- You can use SimpleDateFormat class to format the date in different ways.
Update: If you are working on Java 8, then you should consider using new Date Time API. For more details, please read Java Date Time API Tutorial.