时间比较工具(时、分、秒)|Java

1. 新建 CompareUnit.java

package org.cs.base.utils.enm;

/**
 * 时间比较单位枚举
 * <p>
 * HOUR,   //时
 * <p>
 * MINUTE, //分
 * <p>
 * SECOND  //秒
 *
 * @author admin
 * @since 2022-4-25
 */
public enum CompareUnit {
    HOUR,   //时
    MINUTE, //分
    SECOND  //秒
}

2. 新建 CalendarUtils.java

package org.cs.base.utils;

import org.apache.log4j.Logger;
import org.cs.base.utils.enm.CompareUnit;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * 工具类
 *
 * @author admin
 * @since 2022-04-25
 */
public class CalendarUtils {
   private static Logger log = Logger.getLogger(CalendarUtils.class);
   
    /**
     * 时间比较
     *
     * @param t1   时间1
     * @param t2   时间2
     * @param unit 单位
     * @return
     */
    public static long compareTo(String t1, String t2, CompareUnit unit) {
        long res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        try {
            c1.setTime(simpleDateFormat.parse(t1));
            c2.setTime(simpleDateFormat.parse(t2));
            long m1 = c1.getTime().getTime();
            long m2 = c2.getTime().getTime();
            switch (unit) {
                case SECOND:
                    res = (m1 - m2) / 1000;
                    break;
                case MINUTE:
                    res = (m1 - m2) / 1000 / 60;
                    break;
                case HOUR:
                    res = (m1 - m2) / 1000 / 60 / 24;
                    break;
                default:
                    res = -1L;
                    break;
            }
        } catch (Exception e) {
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(bs));
            log.warn(bs);
            res = -1L;
        }
        return res;
    }
}

3. 测试

public static void main(String[] args) throws ParseException {
    String t1 = "2022/04/25 18:57:05";
    String t2 = "2022/04/25 18:21:01";
    System.out.println("时:" + CalendarUtils.compareTo(t1, t2, CompareUnit.HOUR));
    System.out.println("分:" + CalendarUtils.compareTo(t1, t2, CompareUnit.MINUTE));
    System.out.println("秒:" + CalendarUtils.compareTo(t1, t2, CompareUnit.SECOND));
}

 

posted @ 2022-04-25 19:25  七月的枫丶  阅读(1078)  评论(0编辑  收藏  举报