Wednesday, April 24, 2013

Date and Time Method

    public static String getCurrentDateTime(){
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
        Date date = new Date();
        log.info("Current System Date_Time as : " + dateFormat.format(date));
        return dateFormat.format(date);
    } // end of method
   
    public static void storeCurrentDateTimeinPropertyFile(String currentDateTime) {
        //long hour = 3600 * 1000; // 3600 seconds times 1000 milliseconds
        Properties prop = new Properties();
        try {
            // set the properties value
            prop.setProperty("CurrentDateTime", currentDateTime);
            prop.store(new FileOutputStream(getCurrentDirPath()+"//" +"time.properties"), null);
            log.info("store current start_Date_Time to property file : " +  currentDateTime);
        } catch (IOException ex) {
            ex.printStackTrace();
        } // end of catch
    }
   
    // load from property file and parse to date and then increment it by one second
    public static void incDateTimeByOneSecoud(){
    try {
        Properties prop = loadProperty();
        String startTime = prop.getProperty("StartDateTime");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
        Date date = dateFormat.parse(startTime);
        Date newDt = new Date(date.getTime() + 1000L);
        String newDT = dateFormat.format(newDt).toString();
        prop.setProperty("StartDateTime", newDT);
        prop.store(new FileOutputStream(getCurrentDirPath()+"//" +"time.properties"), null);
        log.info("increment C1_START_DATE_TIME  to property file : " + newDT);
        } catch (Exception ex) {
            ex.printStackTrace();
        } // end of catch
    } // end of method

 // load property file if missing then create new and reload it
private static Properties loadProperty(){
        Properties prop = new Properties();
        try {
            // load a properties file from class path, inside static method
            //prop.load(SyncTimeProperty.class.getClassLoader().getResourceAsStream("config.properties"));
             prop.load(new FileInputStream("time.properties"));
            log.info("loading property file : ");
        } catch (IOException ex) {
            ex.printStackTrace();
            log.info("Creating new property file : ");
            storeCurrentDateTimeinPropertyFile(getCurrentDateTime());
            return loadProperty();
        } // end of catch
        return prop;
    } // end of method

/shift the given Date by exactly 24 hours. 
private final static long MILLISECONDS_PER_DAY = 1000L * 60 * 60 * 24; 
public static void shiftDate(Date d) {
    long time = d.getTime();
    time += MILLISECONDS_PER_DAY;
    d.setTime(time);
}

No comments:

Post a Comment