前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java获取当日的起始时间,结束时间,现在时间,是否在时间段中。

Java获取当日的起始时间,结束时间,现在时间,是否在时间段中。

作者头像
ydymz
发布2018-09-10 16:13:19
1.9K0
发布2018-09-10 16:13:19
举报
文章被收录于专栏:lgp20151222lgp20151222

当日的起始时间

代码语言:javascript
复制
 public static Date getTodayStartTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        return todayStart.getTime();
    }

 结束时间

代码语言:javascript
复制
   public static Date getTodayEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        return todayEnd.getTime();
    }

 现在时间

代码语言:javascript
复制
 public static Date getNowDate() {
        Calendar now = Calendar.getInstance();
        return now.getTime();
    }

 是否在时间段中

写了两种实现,date和localdatetime的两种方式

代码语言:javascript
复制
    public static boolean inTime(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean hourInTime(Date beginTime, Date endTime) {
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        Date nowTime = null;
        try {
            nowTime = df.parse(df.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return inTime(nowTime, beginTime, endTime);
    }

    public static boolean inTime(LocalDateTime time, LocalDateTime beginTime, LocalDateTime endTime) {
        return (time.isAfter(beginTime) && time.isBefore(endTime));
    }

    public static boolean hourInTime(LocalDateTime beginTime, LocalDateTime endTime) {
        return inTime(LocalDateTime.now(), beginTime, endTime);
    }

localdatetime的优点就是代码简洁,但是不方便,因为localdatetime一定是带年月日时分秒的。

而date则方便了许多,可以只比较时分(hourInTime),日(dayInTime),月(monthInTime)之类的,但是date类型大多数方法官方不建议使用。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 当日的起始时间
  •  结束时间
  •  现在时间
  •  是否在时间段中
    • localdatetime的优点就是代码简洁,但是不方便,因为localdatetime一定是带年月日时分秒的。
      • 而date则方便了许多,可以只比较时分(hourInTime),日(dayInTime),月(monthInTime)之类的,但是date类型大多数方法官方不建议使用。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档