Java – How to get current date time – date() and calender()
Written on December 24, 2009 at 8:24 am by
mkyong
In Java, you can get the current date time via 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()));
Please visit this SimpleDateFormat documentation to understand the SimpleDateFormat in details.
Java Code example
Here is the full source code to show the use of date() and calender() to get the current date time.
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())); } }
This article was posted in Java category.
Oracle Magazine - Free Magazine
Oracle Magazine contains technology strategy articles, sample code, tips, Oracle and partner news, how to articles for Java's developers and DBAs, and more.
Securing & Optimizing Linux: The Hacking Solution - Free Guide
A comprehensive collection of Linux security products and explanations in the most simple and structured manner on how to safely and easily configure and run many popular Linux-based applications and services.
The Windows 7 Guide: From Newbies to Pros - Free Guide
In this 46 page guide you will be introduced to Windows 7 and what it has to offer. This guide will go over the software compatible issues, you will learn about the new taskbar, how to use and customize Windows Aero, what Windows 7 Libraries are all about, what software is included in Windows 7, and how easy networking is with Windows 7 along with other topics.
All Java Tutorials
- Java Core Technology - Java RegEx, Java XML, Java I/O, Java Misc
- J2EE Frameworks - Hibernate, Spring 2.5, Spring MVC, Struts 1.x, Struts 2.x
- Build Tools - Maven, Archiva
- Unit Test - jUnit, TestNG
- Client Scripts - jQuery
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