这篇文章主要介绍了java根据时间戳 获取该时间戳所在周 月 年 最后时刻(的时间戳)的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
测试类
public class TestDate { public static void main(String[] args) { TimeData weekTime = DateUtil.getWeekTime(1604542728478l); //2020-11-05 10:18:48 System.out.println(weekTime+" weekTime"); Date date = new Date(1604542728478l); System.out.println(date+" date"); //Thu Nov 05 10:18:48 CST 2020 = 2020-11-05 10:18:48 long monthTime = cn.hutool.core.date.DateUtil.endOfMonth(date).getTime(); System.out.println(monthTime+" monthTime"); //1606751999999 = 2020-11-30 23:59:59 long yearTime = cn.hutool.core.date.DateUtil.endOfYear(date).getTime(); System.out.println(yearTime+" yearTime"); //1609430399999 = 2020-12-31 23:59:59 } }
实体类
@Data @AllArgsConstructor @NoArgsConstructor @ToString public class TimeData { /** * 数据查询的开始时间 */ private Long startTime; /** * 数据查询的结束时间 */ private Long endTime; }
工具类
public class DateUtil { public static TimeData getWeekTime(Long day) { DateTime date = new DateTime(day); //获取周的星期一 //判断周一是否在上个月 //日所在的月 int dayMonth = cn.hutool.core.date.DateUtil.month(date); //周开始所在的月 DateTime beginOfWeek = cn.hutool.core.date.DateUtil.beginOfWeek(date); int beginMonth = cn.hutool.core.date.DateUtil.month(beginOfWeek); //周结束所在的月 DateTime endOfWeek = cn.hutool.core.date.DateUtil.endOfWeek(date); int endMonth = cn.hutool.core.date.DateUtil.month(endOfWeek); DateTime startTime; DateTime endTime; if (beginMonth == endMonth) { //周开始和结束在一个月内 startTime = beginOfWeek; endTime = endOfWeek; } else if (beginMonth == dayMonth) { //周开始和日在一个月内 startTime = beginOfWeek; endTime = cn.hutool.core.date.DateUtil.endOfMonth(date); } else { //周结束和日在一个月内 startTime = cn.hutool.core.date.DateUtil.beginOfMonth(date); endTime = endOfWeek; } endTime.setField(DateField.HOUR_OF_DAY, 23); endTime.setField(DateField.SECOND, 59); endTime.setField(DateField.MINUTE, 59); //判断本周结束时间是否是下个月,是的话 取月结束时间,不是,取周结束时间 return new TimeData(startTime.getTime(), endTime.getTime()); } }