Java - Get date and time
There are multiple ways to get the date and time in Java. This is how you get the current date and time using Date
and Calendar
.
Using java.util.Date
```javaDate date = new Date(); System.out.println(date.toString()); Output: Sat Apr 05 12:28:48 EDT 2014
### Using `java.util.Calendar`
```javaDate calDate = Calendar.getInstance().getTime();
System.out.println(calDate.toString());
Output: Sat Apr 05 12:28:48 EDT 2014
Let’s say we want to get the current date and set the time to 1700h. Code like this will result in deprecated method warnings for Date.setHours(int), Date.setMinutes(int) and Date.setSeconds(int)
.
```javaDate startTime = new Date(); startTime.setHours(17); startTime.setMinutes(0); startTime.setSeconds(0); System.out.println(startTime.toString()); Output: Sat Apr 05 17:00:00 EDT 2014
The correct way to set the time on a Date object is to use `java.util.Calendar` like so:
```javaCalendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 17);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date calStartTime = calendar.getTime();
System.out.println(calStartTime.toString());
Now we have the date and time, let’s use java.text.SimpleDateFormat
and import java.text.DateFormat
to format the date so that it is more human readable.
javaDate rawDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyy HH:mm");
System.out.println(dateFormat.format(rawDate));
Output: 05/13/2014 13:13
The formatting possibilities for the Date
object are infinite; see the references below for links to formatting.
Get the code on GitHub
References:
Date javadocs
Calendar javadocs
SimpleDateFormat javadocs