判断现在、自定义开始时间和自定义结束时间的关系

该博客介绍了Java中FormatTime类用于格式化时间字符串的方法,包括两种重载的formatTime函数,分别处理不同格式的时间。此外,还提供了一个judgeState方法来判断当前时间位于给定的开始和结束时间之间哪种状态,返回值表示现在时间相对于开始和结束时间的位置。
摘要由CSDN通过智能技术生成

FormatTime类:

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

/**
 * @author Canser
 */
public class FormatTime {

    /**
     * 格式化时间字符串并返回Date类型的时间
     *
     * @param time         时间字符串
     * @param formatString 时间格式化类型,可传空值,为空值时默认为"yyyy-MM-dd HH:mm:ss"
     * @return 返回Date类型的时间
     */
    public static Date formatTime(String time, String formatString) {
        try {
            if ("".equals(formatString)) {
                return formatTime(time);
            }
            return new SimpleDateFormat(formatString).parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 格式化时间字符串并返回Date类型的时间
     * 时间格式化类型默认为"yyyy-MM-dd HH:mm:ss"
     *
     * @param time 时间字符串
     * @return 返回Date类型的时间
     */
    public static Date formatTime(String time) {
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

}

判断方法:

     /**
     * 计算开始时间、现在和结束时间的关系
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 当现在在开始时间之前,返回0,当现在在开始时间和结束时间之间,返回1,当现在在结束之间之后,返回2
     */
    private static int judgeState(String startTime, String endTime) {
        Date startDate = FormatTime.formatTime(startTime);
        Date endDate = FormatTime.formatTime(endTime);
        Date nowDate = new Date();
        if (nowDate.compareTo(startDate) < 0) {
            return 0;
        } else if (nowDate.compareTo(endDate) <= 0) {
            return 1;
        } else {
            return 2;
        }
    }

调用:

String startTime = "2021-10-14 14:00:00";
String endTime = "2021-10-14 18:00:00";

int status = judgeState(startTime, endTime);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胡#

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值