Showing posts with label comparision. Show all posts
Showing posts with label comparision. Show all posts

Wednesday, January 30, 2013

Hours comparision in java using SimpleDateFormat


Hour comparision in 24 hour format using SimpleDateFormat overrided compareTo method

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateComparision {
  
    public void isTimeBreached(StringBuilder breachTime){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        Date breachDateTime = null;
        Date systemDateTime = null;
        try {
            breachDateTime = sdf.parse(breachTime.toString());
            Calendar systemCal = Calendar.getInstance();
            systemCal.setTimeInMillis(System.currentTimeMillis());
            systemDateTime = systemCal.getTime();
            System.out.println(systemDateTime+" >> converted to >> "+sdf.format(systemDateTime));
            int value = sdf.format(systemDateTime).compareTo(sdf.format(breachDateTime));
            if(value <= 0){
                System.out.println(sdf.format(systemDateTime)+ " is within time "+sdf.format(breachDateTime));
            }else{
                System.out.println(sdf.format(systemDateTime)+ " breached the time "+sdf.format(breachDateTime));
            }
        } catch (ParseException e) {
            System.err.println("The date should be in HH:mm:ss format:"+breachTime);
            e.printStackTrace();
        }
    }
  
    public static void main(String[] args) {
        try{
            DateComparision dc = new DateComparision();
            StringBuilder breachTime = new StringBuilder("15:00:00");
            dc.isTimeBreached(breachTime);
        }catch(Exception pe){
            pe.printStackTrace();
        }
    }
  
}











output:

1) Thu Jan 01 19:00:00 CST 1970 >> converted to >> 19:00:00
19:00:00 breached the time 15:00:00


2) Changed breached time to 21
Wed Jan 30 20:17:09 CST 2013 >> converted to >> 20:17:09
20:17:09 is within time 21:00:00