【问题标题】:How to get last hour, last month and yesterday in javascript?如何在javascript中获取最后一小时,上个月和昨天?
【发布时间】:2013-05-22 05:13:01
【问题描述】:

我正在尝试从当前日期和时间获取最后一个小时、上个月和昨天,我正在使用 Date() 对象来获取当前日期和时间:

function fetchCurrentDateTime() {
    var currentDateobj = new Date()
    var Day = currentDateobj.getDate()
    var Hour = currentDateobj.getHours()
    var Month = 1+(currentDateobj.getMonth())
    var Year = currentDateobj.getFullYear()
    console.log('Today is:', Day+'-'+Month+'-'+Year);
    console.log('yesterday was:', Day-1+'-'+Month+'-'+Year);
    console.log('Its', Hour, 'hrs');
    console.log('It was', Hour-1, 'an Hour back.');
    console.log('This is:', Month, 'Month');
    console.log('It was', Month-1, 'Month, a month ago.');
    console.log('It is', Year);
    }

我想要一个函数,它不仅可以返回日期或时间,还可以返回完整的日期时间,例如:

Today: '2013-05-21 10:06:22'
Yesterday: '2013-05-20 10:06:22'
Current Hour: '2013-05-21 10:06:22'
Last Hour: '2013-05-21 09:06:22'
Current Month: '2013-05-21 10:06:22'
Last Month: '2013-04-21 10:06:22'

我也想问一下如果小时是00:00:00,那么最后一个小时的结果是什么?月份和日期也是如此。

【问题讨论】:

  • 你的意思是这样的?:jsfiddle.net/dGvc3
  • 我的意思是我不想制作像year+'-'+month+'-'+day这样的字符串

标签: javascript date datetime datetime-format


【解决方案1】:
var today = new Date();
var yesterday = new Date(today.getTime() - (1000*60*60*24));
var hourago = new Date(today.getTime() - (1000*60*60));

console.log(today);
console.log(yesterday);
console.log(hourago);

getTime() 返回您的 Date 对象的时间戳。然后,您可以减去适当的毫秒数并从该数字中创建一个新对象。如果需要,您现在可以按照您希望的方式设置日期格式。

【讨论】:

  • @Squeezy:你能帮我把结果格式化成:'2013-05-21 10:06:22',而时间戳看起来像:Date {Wed May 22 2013 11:02:03 GMT+0500 (PKT)}
  • 看看datejs.com这可能会一次性解决你的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 2015-04-03
相关资源
最近更新 更多