Tuesday, August 21, 2012

Get Current Date and time

  • We usually need to get current date and time in java class. It is easy to get current date for java.util.Date class.

java.util.Date date = new java.util.Date();

  • This date object gives current date and time. To use this date and time this can be formatted in needed date format as follows:

DateFormat dateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            java.util.Date date = new java.util.Date();
            String datetime = dateFormat.format(date);

  • This will give desired format to current date. Now to use this format in code we need to change this string to java.util.Date

        try{
                java.util.Date date2 = dateFormat.parse (datetime);
                }catch(ParseException pe){
                    pe.printStackTrace();}

  • Now to get current date in oracle.jbo.domain.Date class do the following

        java.sql.Timestamp datetime = new java.sql.Timestamp(System.currentTimeMillis());
        oracle.jbo.domain.Date daTime = new  oracle.jbo.domain.Date(datetime);  

  • Or change java.util.Date to oracle.jbo.domain.Date
               DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                    java.util.Date date = new java.util.Date();
                    String dateStr = dateFormat.format(date);
         try{
                java.util.Date date2 = dateFormat.parse (dateStr);
                    java.sql.Date sqldate = new java.sql.Date(date2.getTime());
                    oracle.jbo.domain.Date daTime = new  oracle.jbo.domain.Date(sqldate);
                    System.out.println("Current Date Time : jbo " + daTime);
                }catch(ParseException pe){
                    pe.printStackTrace();}  

To get only date use java.sql.Date and to get date with time use java.sql.Timestamp

No comments:

Post a Comment