Monday, September 21, 2015

Get current time using java Date class

Creating a Date object with java

When we create a new Date object with default constructor, jvm creates a date object with current time stamp. ( according to local time zone )  

import java.util.Date;
class Demostration{
 public static void main(String[]args){
  Date date=new Date(); // date object
  System.out.println(date); // try to print the date object   
 } 
}






This will give you a output similar to the following

Mon Sep 21 23:29:08 IST 2015


Most of the methods in java.util.Date class are deprecated with the arrival of the java Calendar class, so the next most important method of Date class is the getTime() method.

import java.util.Date;
public class Main {
    public static void main(String[]args){
        Date date =new Date();
        long timeInMilliSeconds=date.getTime();
        System.out.println(timeInMilliSeconds);
    }
}

getTime() method returns the number of milliseconds since January 1, 1970, 00:00:00 GMT,
don't worry you'll understand why this is important when you are trying to compare time.

Create a data object with given time (time in milliseconds )

Also you can create a date object providing long argument for the constructor as well.

import java.util.Date;
public class Main {
    public static void main(String[]args){
        Date date =new Date(234567);
        System.out.println(date);
    }
}

see the output and you'll understand.

As I told you earlier most of the methods of Date class are deprecated now, you can see my other article to learn about Calendar class and how to use both Date and the Calendar.

Your comments and suggestions are welcome.

No comments:

Post a Comment