简体   繁体   English

使用moment.js来确定unix时间戳是否在上周内

[英]Use moment.js to figure out if a unix timestamp was within the last week

How do i use unix timestamp to work out if an event was within the last week? 如果活动在上周之内,我如何使用unix时间戳进行计算?

I tried 我试过了

moment().subtract('weeks', 1).unix()<item.start

but it is returning unexpected results. 但是它返回了意外的结果。 thanks so much 非常感谢

edit: thanks so much for the question feedback here is an example of my response 编辑:非常感谢您的问题反馈,这是我的回复示例

1537858386 1540197758000 1537858386 1540197758000

You can create the point of time which represents the lowest valid value as you did before. 您可以像以前一样创建代表最低有效值的时间点。 When you have this point in time, you can check with momentjs if a given date is older. 当您有这个时间点时,可以使用momentjs检查给定的日期是否较早。

const weekAgo = moment().subtract(1, 'weeks') // This is the time to check

const ts = 1519945200000 // any unix timestamp. This is 2018-03-01
const m1 = moment(ts) // Use a unixtimestamp to create a moment object

const m2 = moment().subtract(8, 'days') // further test data
const m3 = moment().subtract(6, 'days') // further test data

console.log(weekAgo.isBefore(m1)) // true
console.log(weekAgo.isBefore(m2)) // true
console.log(weekAgo.isBefore(m3)) // false

You can check this answer for date range checking 您可以检查此答案以进行日期范围检查

You can use one of the moment plugin -> moment-range to deal with date range: 您可以使用moment plugin -> moment-range来处理日期范围:

 var startDate = new Date(2013, 1, 12)   , endDate   = new Date(2013,
 1, 15)   , date  = new Date(2013, 2, 15)   , range =
 moment().range(startDate, endDate);

 range.contains(date); // false

Will be using moment.diff function 将使用moment.diff函数

Follow these Steps 跟着这些步骤

  1. Convert unix timestam to moment object 将unix timestam转换为moment对象
  2. Format date 格式化日期
  3. use moment.diff 使用moment.diff

     function dateDiff (date) { // date is unix timestamp date let d = moment(date); if ( d.isValid() ) { d.format("YYYY-MM-DD"); // moment() gives current date-time return moment().diff(d, 'weeks', true); // If past date then result will be positive if future date then negative. } else return null; } console.log( dateDiff( 1519945200000 ) ); // 30.648079404761905 // 30 weeks ago console.log( dateDiff( 1534395200000 ) ); // 6.755883640873016 // 6 weeks ago console.log( dateDiff( 1529945200000 ) ); // 14.113687873677248 // 14 weeks ago console.log( dateDiff( 1541945200000 ) ); // -5.7275819675925925 // 5 weeks in future 

As @be-ndee said it was just milliseconds vs seconds so i just edited it to 正如@ be-ndee所说,这只是毫秒与秒,所以我将其编辑为

moment().subtract('weeks', 1).unix() moment()。subtract('weeks',1).unix()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM