作者最近在公司的项目中又遇到了一个难题,在订单这一块需要查询三个月内的所有订单,作者是今年刚毕业的码农实习生。第一次接触这种东西。刚接到手的时候是一脸懵逼,不知道该如何做,没有一些想法,然后跑去问候了度娘,但是度娘脾气挺大的,没告诉我怎么实现的,却给我提供了一些思路。
思路:既然要获取三个月前的时间,那么获取现在的时间是很有必要的。这里利用了一个 JS Date 对象的一些知识点利用现在的时间算出了三个月前的时间。
具体如何实现作者在下面提供了一些完成的代码。各种注释可谓是一看就会的,所以接下来还是好好的读一读代码就可以理解了。作者个人因为菜,所以各路大神如果还有啥修改意见或者有另外一种解决方案欢迎在下面留言,作者会一一回复,并且会尝试各路大神的想法和思路等等,废话就不扯了,下面贴出源代码。可直接复制粘贴使用,如果有兴趣也可以研究一下,(大神请自动忽略)
getThreeMonths () {
// let timeOne = new Date(1575158521000)
let timeOne = new Date()
let year = timeOne.getFullYear()
let month = timeOne.getMonth() + 1
let day = timeOne.getDate()
let hours = timeOne.getHours()
let minutes = timeOne.getMinutes()
let seconds = timeOne.getSeconds()
console.log(`现在的时间是:${year}-${month}-${day} ${hours}:${minutes}:${seconds}`)
// 计算3个月后的月份
let ThreeMonths = month - 3
// 如果小于 0 说明是去年
if (ThreeMonths <= 0) {
year = year - 1
}
// 如果 等于 -2 说明当前月是 1 月份 所以三个月前是去年 10月
if (ThreeMonths === -2) {
ThreeMonths = 10
}
// 如果 等于 -1 说明当前月是 2 月份 所以三个月前是去年 11月
if (ThreeMonths === -1) {
ThreeMonths = 11
}
// 如果 等于 0 说明当前月是 3 月份 所以三个月前是去年 12月
if (ThreeMonths === 0) {
ThreeMonths = 12
}
// 获取当前的时间的日期字符串
// **如果天数的值为零,则默认返回当前月份的最后一天
let timeTow = new Date(year, ThreeMonths, 0, hours, minutes, seconds)
// 获取三个月前的最后一天
let ThreeMonthsDay = timeTow.getDate()
// 获取三个月前的小时数
let ThreeMonthsHour = timeTow.getHours() < 10 ? '0' + timeTow.getHours() : timeTow.getHours()
// 获取三个月前的分钟数
let ThreeMonthsMinutes = timeTow.getMinutes() < 10 ? '0' + timeTow.getMinutes() : timeTow.getMinutes()
// 获取三个月前的秒数
let ThreeMonthsSeconds = timeTow.getSeconds() < 10 ? '0' + timeTow.getSeconds() : timeTow.getSeconds()
// 判断如果当前月份的天数大于三个月前的天数时,则当前天数等于三个月前的天数
if (day > ThreeMonthsDay) {
day = ThreeMonthsDay
}
day = day < 10 ? '0' + day : day
console.log(`三个月前的时间是:${year}-${ThreeMonths}-${day} ${ThreeMonthsHour}:${ThreeMonthsMinutes}:${ThreeMonthsSeconds}`)
// 格式化时间
const THREE_MONTHS_AGO = `${year}/${ThreeMonths}/${day} ${ThreeMonthsHour}:${ThreeMonthsMinutes}:${ThreeMonthsSeconds}`
// 生成时间戳
const THREE_STAMP = new Date(THREE_MONTHS_AGO).getTime()
return THREE_STAMP
}
结语:在本文的最后作者也唠嗑两句,作者写的代码绝对没有抄袭或者复制别人的代码,作者写的代码都是经过自己的思考。不断的踩坑踩出来的代码。所以不存在复制别人的博客拿来就用。