Java Date & Time

Java Date class is one of the Java’s oldest class, and most of the methods in the class are deprecated, but we can still use it to represent a date though.
Instantiate a java.util.Date instance :
Example:
java.util.Date date = new java.util.Date();
or
public class DisplayDate {
   public static void main(String args[]) {
       // Instantiate an object
       Date date = new Date();
   }
}
date and time contained in a java.util.Date instance, and accessible by using predefined methods.

Current timestamp

Date time timestamp in milliseconds is accessible by using Date object with getTime() method.
Example:
import java.util.Date;

public class DisplayDate {
   public static void main(String args[]) {
       // Instantiate an object
       Date date = new Date();
        
       // display current timestamp
       System.out.println(date.getTime());
   }
}
Program Output:
1444194469602

Current Date & Time

Date time timestamp in milliseconds is accessible by using Date object with toString() method.
Example:
import java.util.Date;

public class DisplayDate {
   public static void main(String args[]) {
       // Instantiate an object
       Date date = new Date();
        
       // display time and date
       System.out.println(date.toString());
   }
}
Program Output:
Wed Oct 07 05:16:16 UTC 2015

Comparing Dates

Date Formatting

SimpleDateFormat() method is used to formatting and parsing dates in a locale-sensitive manner. Its returning date-time formatting by user-defined pattern.
Example:
import java.util.Date;
import java.text.*;

public class DisplayDate {
   public static void main(String args[]) {
      Date date = new Date( );
      SimpleDateFormat dateFormat = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");

      System.out.println("Current Date: " + dateFormat.format(date));	
       
   }
}
Program Output:

Current Date: Wed 2015.10.07 at 05:48:19 AM UTC

1 comment:

  1. NIIT java projects go to => http://mkniit.blogspot.in

    ReplyDelete