Come sottrarre i minuti da una data in javascript?


134

Come posso tradurre questo pseudo codice in js funzionanti [non preoccuparti da dove viene la data di fine tranne che è una data javascript valida].

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 - durationInMuntes;

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

Risposte:


200

Una volta che lo sai:

  • Puoi creare un Datechiamando il costruttore con millisecondi dal 1 ° gennaio 1970.
  • La valueOf()a Dateè il numero di millisecondi dal 1 ° gennaio 1970
  • Ci sono 60,000millisecondi in un minuto: -]

... non è così difficile.

Nel codice seguente, Dateviene creato un nuovo sottraendo il numero appropriato di millisecondi da myEndDateTime:

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

6
Ma non gestisce quando aggiungi minuti. Per gestire correttamente quando aggiungi minuti, dovresti usare .getTime(). Esempio:var myStartDate = new Date(myEndDateTime.getTime() + durationInMinutes * MS_PER_MINUTE);
Gabriel L. Oliveira,

Puoi anche usare var myStartDate = somedate.addMinutes(-durationInMuntes);Suppongo che somedate sia un oggetto Date
kubahaha,

1
Funziona ... ma hai una domanda sul fatto che il costruttore Date () abbia 3 opzioni, ovvero 1: vuoto 2: stringa e 3: numero anno, numero mese .... quindi quello in uso sopra segue quale costruttore?
Zafar,


Per un esempio di come ciò possa andare storto, usando Europa / Londra come locale del fuso orario: var d = new Date("2017-10-29 01:50:00"), e = new Date(d.getTime() + 20 * 60000);ti aspetteresti edi essere 02:10:00, giusto? No. 01:10:00. DST saluta. E poi ci sono secondi bisestili ...
Niet the Dark Absol,

81

Puoi anche usare get e impostare i minuti per raggiungerlo:

var endDate = somedate;

var startdate = new Date(endDate);

var durationInMinutes = 20;

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

52
vale la pena notare che setMinutes()è abbastanza intelligente da gestire correttamente i minuti negativi. Quindi, se la data di inizio fosse 3:05 e desideri sottrarre 30 minuti, -25passeresti a setMinutes (), che è abbastanza intelligente da sapere che lo 3:-25è 2:35. (cioè non genera un'eccezione.)
Kip

2
@Kip - Grazie, questa è l'intuizione che rende utile questa risposta. Ma tutti i browser lo garantiscono? Chiedo perché MDN dice che sono ammessi solo 0 - 59 - ma sospetto che i documenti siano sbagliati in questo caso? Vedi: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
Justin Ethier

Questo mi è stato più utile, volevo sottrarre il tempo da un'istanza dell'oggetto Date esistente che è stata impostata in un modo particolare attraverso il costruttore. Grazie!
Bill Effin Murray,

1
Basta ricordare che la .setMinutes(...)forza gestisce i intvalori. Se si imposta 1.5 minutesin un Date, imposterà 1 minutee manterrà solo i secondi come prima.
Gabriel L. Oliveira,

Stavo ottenendo valori errati in un caso d'uso simile quando ho provato startDate = endDate. Sembra il problema in cui si verifica una copia superficiale
raghav710

35

Tutto è solo tick, non c'è bisogno di memorizzare i metodi ...

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

o

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

aggiornare

Dopo aver lavorato con momentjs, devo dire che questa è una libreria straordinaria che dovresti dare un'occhiata. È vero che le zecche funzionano in molti casi rendendo il tuo codice molto piccolo e dovresti cercare di rendere il tuo codice il più piccolo possibile per quello che devi fare. Ma per qualsiasi cosa complicata, usa momentjs.


2
IMO non è così semplice. Ci vuole un po 'di sforzo per decifrare cosa fa effettivamente questo codice. L'approccio migliore è avvolgere quel tipo di logica in una funzione.
sszarek,

12

moment.js ha alcuni metodi di praticità davvero piacevoli per manipolare gli oggetti data

Il metodo .subtract , consente di sottrarre una certa quantità di unità di tempo da una data, fornendo l'importo e una stringa di unità di tempo.

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 ...

6

Questo è quello che ho trovato:

//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);

fonti:

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

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


5
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.

puoi convertire il timestamp di Unix in tempo convenzionale usando new Date().per esempio

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

Ho apportato alcune modifiche alla formattazione. Assicurati che rifletta ancora ciò che intendevi pubblicare.
adiga,

1

Prova come di seguito:

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

0

Questo è quello che ho fatto: vedi su 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;
    }
}

OP non usa new Date(), ma ha una data specifica e ha chiesto solo di sottrarre i minuti. Inoltre, il codice non funziona: restituisce il timestamp UNIX anziché l'oggetto Date.
Michał Perłakowski,

0

Estendi la classe Date con questa funzione

// 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;
};

Quindi puoi aggiungere o sottrarre un numero di minuti, secondi, ore, giorni ... a qualsiasi data.

add_10_minutes_to_current_date = Date.dateAdd( Date(), 10, "m");
subs_1_hour_to_a_date = Date.dateAdd( date_value, -1, "h");
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.