Monday, April 19, 2010

Getting current date and time in java

When you are programming something you may need the current date and current time, say like while naming the reports you want to include the date and time at which the report was generated, so in this case you want to write code that will generate the current date and time. This is a very basic thing and every java programmer should know this.

We will be using two important classes for this...
1. java.util.Calendar
2. java.text.SimpleDateFormat

And here goes the simple code...

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy - HH:mm:ss");
Instead of " : " you can have " _ " or any other such differentiator it doesn''t matter. But you need to take care of the Caps of "MM" and "HH". Also note that "YYYY" will not work. Try yourself for everything else..
Most importantly note that we are passing the current time as a parameter to the format function of SimpleDateFormat.

No comments: