js传入一个时间戳判断是否是今天
时间: 2024-03-27 09:37:02 浏览: 87
JS获取当前时间戳方法解析
5星 · 资源好评率100%
可以通过以下步骤判断一个时间戳是否是今天:
1. 获取当前时间的时间戳(单位为秒):
```
var now = Math.floor(Date.now() / 1000);
```
2. 获取传入的时间戳对应的日期:
```
var date = new Date(timestamp * 1000);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
```
3. 获取当前日期对应的年月日:
```
var today = new Date();
var todayYear = today.getFullYear();
var todayMonth = today.getMonth() + 1;
var todayDay = today.getDate();
```
4. 比较传入的日期和当前日期是否相同:
```
if (year === todayYear && month === todayMonth && day === todayDay) {
// 时间戳对应的日期是今天
} else {
// 时间戳对应的日期不是今天
}
```
完整代码如下:
```
function isToday(timestamp) {
var now = Math.floor(Date.now() / 1000);
var date = new Date(timestamp * 1000);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var today = new Date();
var todayYear = today.getFullYear();
var todayMonth = today.getMonth() + 1;
var todayDay = today.getDate();
return year === todayYear && month === todayMonth && day === todayDay;
}
```
调用方式:
```
console.log(isToday(1614152990)); // true or false
```
阅读全文