函数的日期类 Date DateTime Time 本质都是 存储了,毫秒级别的时间戳。
一个标准的时间字符串 (如
2019-10-15 20:48:19.128) 就占用了 23 个字节,比较浪费。所以计算机中也使用一种称为 epoch time 的存储方式,存储的是当前时间(转换为 UTC) 距离 Unix epoch (1970-01-01 00:00:00) 的毫秒数,例如上例可表示为 1571172499000。这样要表示日常生活中的时间,通常只需要 4 个字节(32位) 或是 8 个字节(64位) 即可。当然,存储节省了,能表示的时间范围也小了,例如 32 位的 epoch time 最多只能表示到 2038-01-19时间戳转换网站:https://tool.lu/timestamp/
一些代码示例
//获取上个月的第一天和最后一天//获取上个月的第一天和最后一天
Date newDate = Date.now();
Date date = newDate.withYear(2023)
.withMonth(1)
.withDay(20)
Date firstDayOfMonth = (date - 1.months).toStartOfMonth()
Date lastDayOfMonth = date.withMonth(date.getMonth()).withDay(1) - 1.days
log.info(firstDayOfMonth)
log.info(lastDayOfMonth)//日期转时间戳 long toTimestamp = date.toTimestamp() 时间戳转Date/DateTime DateTime dateTime = DateTime.of(toTimestamp) Date date = Date.of(toTimestamp) //DateTime 同理,API 两个对象都有 Date date = Date.now() //直接设置年月日,API 不会修改原始的调用对象,而是返回一个新日期对象 Date newDate = date.withYear(2019) .withMonth(1) .withDay(1) //计算本月最后一天 //先设置月,日为下一个月的第一天,然后减去一天,就可以获得某一个月份最后一天 Date firstDayOfMonth = date.withMonth(date.getMonth() + 1).withDay(1) - 1.days Fx.log.info(firstDayOfMonth) //DateTimeDuration 持续时间类, 相比 1.months 1.days 1.hours 1.minutes 的区别是,可以使用计算出来的变量 //设置年 DateTimeDuration yearDuration = DateTimeDuration.Years(1) //设置月 DateTimeDuration monthsDuration = DateTimeDuration.Months(1) //设置日 DateTimeDuration dayDuration = DateTimeDuration.Days(1) // 设置时 // DateTimeDuration.Hours(1) // 设置分 // DateTimeDuration.Minutes(1) // 日期支持加减 Date after = date - yearDuration - monthsDuration + dayDuration Fx.log.info(after) Date date = Date.now() //直接用时间戳相加,单位是毫秒,这里就是 一小时 3600 秒 * 1000 毫秒,相当于加了一个小时 long toTimestamp = date.toTimestamp() + 3600 * 1000 DateTime dateTime = DateTime.of(toTimestamp) Fx.log.info(dateTime) // 函数的日期类 Date DateTime Time 本质都是 存储了,毫秒级别的时间戳。
// 需要保证 after > before 如果小于,交换一下两个日前引用
Date before = "2021-03-17"
Date after = Date.now()
Integer beforeWeek = before.dayOfWeek
Integer afterWeek = after.dayOfWeek
Integer minus = afterWeek - beforeWeek
// 先计算相同的周数 的日期
Date tempDate = null
if( minus<0 ){
tempDate = after - DateTimeDuration.Days(minus)
}else{
tempDate = after + DateTimeDuration.Days(minus)
}
//相同周数的日期 想减 / 7 可以直接算出 一共有几周 * 2 就可以算出周六日的天数
Integer weekDate = (((tempDate - before) / 7) as Integer) * 2
Fx.log.info(weekDate)
Fx.log.info(after - before)
Fx.log.info(after - before - weekDate)
return "success"