如何在 JavaScript 中从日期中减去分钟?

问题描述 投票:0回答:9

我怎样才能将这个伪代码翻译成工作JS[不用担心结束日期来自哪里,除了它是一个有效的JavaScript日期]。

var myEndDateTime = somedate;  //somedate is a valid JS date  
var durationInMinutes = 100; //this can be any number of minutes from 1-7200 (5 days)

//this is the calculation I don't know how to do
var myStartDate = somedate - durationInMinutes;

alert("The event will start on " + myStartDate.toDateString() + " at " + myStartDate.toTimeString());
javascript
9个回答
274
投票

一旦你知道了这一点:

  • 您可以通过从 1970 年 1 月 1 日起以毫秒为单位调用
    构造函数
    来创建 Date
  • valueOf()
    a
    Date
    是自 1970 年 1 月 1 日以来的毫秒数
  • 一分钟有
    60,000
    毫秒:-]

在下面的代码中,通过从

Date
中减去适当的毫秒数来创建新的
myEndDateTime

var MS_PER_MINUTE = 60000;
var myStartDate = new Date(myEndDateTime - durationInMinutes * MS_PER_MINUTE);

135
投票

您还可以使用 get 和 set 分钟来实现:

var endDate = somedate;

var startdate = new Date(endDate);

var durationInMinutes = 20;

startdate.setMinutes(endDate.getMinutes() - durationInMinutes);

88
投票

只是蜱虫

刻度表示自 1970 年 1 月 1 日 0:0:0 UTC 以来的毫秒数。日期构造函数可以将数字作为单个参数,该参数被解释为刻度。

当处理毫秒/秒/小时/天数(静态量)时,您可以这样做

const aMinuteAgo = new Date( Date.now() - 1000 * 60 );

const aMinuteLess = new Date( someDate.getTime() - 1000 * 60 );

然后让 JavaScript 显示日期并关心它是星期几或月份和年份等。您可以选择本地化它或使用 Intl 将其本地化。

当你做的事情比上面提到的更复杂,需要任意时区或闰年或月份等时,我建议使用 luxon 进行 JavaScript 相关项目。


17
投票

moment.js 有一些非常好的便捷方法来操作日期对象

.subtract 方法允许您通过提供金额和时间单位字符串从日期中减去一定量的时间单位。

var now = new Date();
// Sun Jan 22 2017 17:12:18 GMT+0200 ...
var olderDate = moment(now).subtract(3, 'minutes').toDate();
// Sun Jan 22 2017 17:09:18 GMT+0200 ...

Luxon还有一个API来操作它自己的

DateTime
对象

var dt = DateTime.now(); 
// "1982-05-25T00:00:00.000Z"
dt.minus({ minutes: 3 });
dt.toISO();              
// "1982-05-24T23:57:00.000Z"

9
投票

这是我发现的:

//First, start with a particular time
var date = new Date();

//Add two hours
var dd = date.setHours(date.getHours() + 2);

//Go back 3 days
var dd = date.setDate(date.getDate() - 3);

//One minute ago...
var dd = date.setMinutes(date.getMinutes() - 1);

//Display the date:
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var date = new Date(dd);
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
var displayDate = monthNames[monthIndex] + ' ' + day + ', ' + year;
alert('Date is now: ' + displayDate);

来源:

http://www.javascriptcookbook.com/article/Perform-date-manipulations-based-on-adding-or-subtracting-time/

https://stackoverflow.com/a/12798270/1873386


8
投票
var date=new Date();

//here I am using "-30" to subtract 30 minutes from the current time.
var minute=date.setMinutes(date.getMinutes()-30); 

console.log(minute) //it will print the time and date according to the above condition in Unix-timestamp format.

您可以使用

new Date()
将 Unix 时间戳转换为常规时间。例如

var extract=new Date(minute)
console.log(minute)//this will print the time in the readable format.

6
投票

尝试如下:

var dt = new Date();
dt.setMinutes( dt.getMinutes() - 20 );
console.log('#####',dt);

2
投票

使用此函数扩展 Date 类

// Add (or substract if value is negative) the value, expresed in timeUnit
// to the date and return the new date.
Date.dateAdd = function(currentDate, value, timeUnit) {

    timeUnit = timeUnit.toLowerCase();
    var multiplyBy = { w:604800000,
                     d:86400000,
                     h:3600000,
                     m:60000,
                     s:1000 };
    var updatedDate = new Date(currentDate.getTime() + multiplyBy[timeUnit] * value);

    return updatedDate;
};

因此您可以对任何日期添加或减去分钟数、秒数、小时数、天数……。

add_10_minutes_to_current_date = Date.dateAdd( Date(), 10, "m");
subs_1_hour_to_a_date = Date.dateAdd( date_value, -1, "h");

1
投票

这就是我所做的:参见Codepen

var somedate = 1473888180593;
var myStartDate;
//var myStartDate = somedate - durationInMuntes;

myStartDate = new Date(dateAfterSubtracted('minutes', 100));

alert("The event will start on " + myStartDate.toDateString() + " at " + myStartDate.toTimeString());

function dateAfterSubtracted(range, amount){
    var now = new Date();
    if(range === 'years'){
        return now.setDate(now.getYear() - amount);
    }
    if(range === 'months'){
        return now.setDate(now.getMonth() - amount);
    }
    if(range === 'days'){
        return now.setDate(now.getDate() - amount);
    }
    if(range === 'hours'){
        return now.setDate(now.getHours() - amount);
    }
    if(range === 'minutes'){
        return now.setDate(now.getMinutes() - amount);
    }
    else {
        return null;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.