欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 时间工具类 获取当前时间,时间比较

程序员文章站 2022-07-15 10:01:30
...
package com.program.face.util;

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

/**
 * @Author: hao
 * @Description: 时间工具类
 * @Date: 2020/4/2 18:55
 * @Version: 1.0
 */
public class DateUtil {
    public static String getCurrentTime() {
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd HH:mm";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        return sdf.format(date);
    }

    public static String getToday() {
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        return sdf.format(date);
    }

    public static String getCurrentHHMMTime() {
        Date date = new Date();
        String strDateFormat = "HH:mm";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        return sdf.format(date);
    }

    /**
     * time1 - time2
     *
     * @param time1 HH:mm
     * @param time2 HH:mm
     * @return
     */
    public static int compareTime(String time1, String time2) {
        int compareResult;
        String[] time1PartArray = time1.split(":");
        int time1Hour = Integer.parseInt(time1PartArray[0]);
        int time1Minute = Integer.parseInt(time1PartArray[1]);
        String[] time2PartArray = time2.split(":");
        int time2Hour = Integer.parseInt(time2PartArray[0]);
        int time2Minute = Integer.parseInt(time2PartArray[1]);
        if (time1Hour > time2Hour) {
            compareResult = 1;
        } else if (time1Hour < time2Hour) {
            compareResult = -1;
        } else {
            if(time1Minute > time2Minute){
                compareResult = 1;
            } else if(time1Minute < time2Minute){
                compareResult = -1;
            } else {
                compareResult = 0;
            }
        }

        return compareResult;
    }
}

 

相关标签: # 存储