Java – How to get current date time – date() and calender()
Written on
December 24, 2009 at 8:24 am by
mkyong
Current date time can be retrieve in java with three classes – SimpleDateFormat(), Date() or Calender().
1. Date() + SimpleDateFormat()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); System.out.println(dateFormat.format(date));
2. Calender() + SimpleDateFormat()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Calendar cal = Calendar.getInstance(); System.out.println(dateFormat.format(cal.getTime()));
P.S Please access java documentation here to understand more date time format in SimpleDateFormat
http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html
Java Code
Here is the full source code of how to get current date time – date() and calender()
package com.mkyong; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; public class GetCurrentDateTime { public static void main(String[] args) { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); //get current date time with Date() Date date = new Date(); System.out.println(dateFormat.format(date)); //get current date time with Calendar() Calendar cal = Calendar.getInstance(); System.out.println(dateFormat.format(cal.getTime())); } }


1. Calendar.getInstance() is noticeably more expensive than new Date(). Not that one shouldn’t use it – it has many important capabilities. But in this comparison, that’s relevant
2. SimpleDateFormat is not thread safe. This isn’t relevant here, but this bites so many people, I mention it by reflex