Monday, April 2, 2012

how to get current date in java

how to get current date in java



  1. /*
  2.   Get current date time values using Java Calendar
  3.   This example shows how to get current date and time values
  4.   using Java Calendar class.
  5. */
  6.  
  7. import java.util.Calendar;
  8.  
  9. public class GetCurrentDateTimeExample {
  10.  
  11.   public static void main(String[] args) {
  12.    
  13.     //get instance of Calendar class
  14.     Calendar now = Calendar.getInstance();
  15.    
  16.     /*
  17.      * Calendar class has several contstants which represents current date
  18.      * and time values
  19.      */
  20.      
  21.     //get current date, year and month
  22.     System.out.println("Current Year is : " + now.get(Calendar.YEAR));
  23.     //month start from 0 to 11
  24.     System.out.println("Current Month is : " + (now.get(Calendar.MONTH) + 1 ));
  25.     System.out.println("Current Date is : " + now.get(Calendar.DATE));
  26.  
  27.     //get current time information
  28.     System.out.println("Current Hour in 12 hour format is : "                        
  29.                     + now.get(Calendar.HOUR));
  30.     System.out.println("Current Hour in 24 hour format is : "
  31.                     + now.get(Calendar.HOUR_OF_DAY));
  32.     System.out.println("Current Minute is : " + now.get(Calendar.MINUTE));
  33.     System.out.println("Current Second is : " + now.get(Calendar.SECOND));
  34.     System.out.println("Current Millisecond is : " + now.get(Calendar.MILLISECOND));
  35.    
  36.    
  37.     //display full date time
  38.     System.out.println("Current full date time is : " +
  39.                 (now.get(Calendar.MONTH) + 1)
  40.                 + "-"
  41.                 + now.get(Calendar.DATE)
  42.                 + "-"
  43.                 + now.get(Calendar.YEAR)
  44.                 + " "
  45.                 + now.get(Calendar.HOUR_OF_DAY)
  46.                 + ":"
  47.                 + now.get(Calendar.MINUTE)
  48.                 + ":"
  49.                 + now.get(Calendar.SECOND)
  50.                 + "."
  51.                 + now.get(Calendar.MILLISECOND)
  52.                 );        
  53.   }
  54. }
  55.  
  56. /*
  57. Typical output would be
  58. Current Year is : 2007
  59. Current Month is : 12
  60. Current Date is : 25
  61. Current Hour in 12 hour format is : 6
  62. Current Hour in 24 hour format is : 18
  63. Current Minute is : 28
  64. Current Second is : 54
  65. Current Millisecond is : 797
  66. Current full date time is : 12-25-2007 18:28:54.797
  67. */

    enjoy it............

0 comments:

Post a Comment

mobile here

Popular Posts