get Hour Difference Between Time - Java java.util

Java examples for java.util:Hour

Description

get Hour Difference Between Time

Demo Code


//package com.java2s;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class Main {
    private static SimpleDateFormat sdf_YYMMDD_HHMMSS = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss", Locale.CHINA);

    public static int getHourDifferenceBetweenTime(String start) {
        return getHourDifferenceBetweenTime(start,
                getCurrentTimeYYMMDD_HHMMSS());
    }//from w w w  .  j  a  va  2  s  .c  o m

    public static int getHourDifferenceBetweenTime(String start, String end) {
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(sdf_YYMMDD_HHMMSS.parse(start));
            c2.setTime(sdf_YYMMDD_HHMMSS.parse(end));
            return (int) Math.abs(c1.getTimeInMillis()
                    - c2.getTimeInMillis()) / 3600000;
        } catch (ParseException pe) {
            pe.printStackTrace();
            return 0;
        }
    }

    public static String getCurrentTimeYYMMDD_HHMMSS() {
        return sdf_YYMMDD_HHMMSS.format(new Date());
    }
}

Related Tutorials