How to Subtract Date/Time in JavaScript

How to subtract date/time in JavaScript?

This will give you the difference between two dates, in milliseconds

var diff = Math.abs(date1 - date2);

In your example, it'd be

var diff = Math.abs(new Date() - compareDate);

You need to make sure that compareDate is a valid Date object.

Something like this will probably work for you

var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));

i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.

How to subtract days from a plain Date?

Try something like this:

 var d = new Date();
d.setDate(d.getDate()-5);

Note that this modifies the date object and returns the time value of the updated date.

var d = new Date();
document.write('Today is: ' + d.toLocaleString());
d.setDate(d.getDate() - 5);
document.write('<br>5 days ago was: ' + d.toLocaleString());

Subtract days, months, years from a date in JavaScript

You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.

You need to individually add/remove unit of time in date object

var date = new Date();
date.setDate( date.getDate() - 6 );
date.setFullYear( date.getFullYear() - 1 );
$("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));

How do I subtract minutes from a date in JavaScript?

Once you know this:

  • You can create a Date by calling the constructor with milliseconds since Jan 1, 1970.
  • The valueOf() a Date is the number of milliseconds since Jan 1, 1970
  • There are 60,000 milliseconds in a minute :-]

In the code below, a new Date is created by subtracting the appropriate number of milliseconds from myEndDateTime:

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

How do i subtract time from a datetime-local input?

You have to make use of the Date Object.

  1. Pass the input as a Date object
  2. Set the new date by subtracting hours and minutes as necessary

Side Note: If you have more complex operations which include dates, you can make use of a third-party library like Moments Js

function myFunction() {
var x = document.getElementById("meeting-time").value;
var date = new Date(x); // parse date as a Date object: TODO: Error handling -> sanitize the input
date.setHours(date.getHours() - 9); // change the date object by subtracting hours from the same date object
date.setMinutes(date.getMinutes() - 30); // change the date object by subtracting minutes from the same date object
document.getElementById("demo").innerHTML = date;
}
<input type="datetime-local" id="meeting-time" name="meeting-time">
<button onclick="myFunction()">click to print time</button>
<p id="demo"></p>

How to add/subtract dates with JavaScript?

Code:

var date = new Date('2011', '01', '02');alert('the original date is ' + date);var newdate = new Date(date);
newdate.setDate(newdate.getDate() - 7); // minus the date
var nd = new Date(newdate);alert('the new date is ' + nd);

How to subtract 2 hours from user's local time?

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);
  • Complete reference list for Date object

How to subtract or add GMT number from new Date in JavaScript?

Note: "Support for RFC 2822 format strings is by convention only." MDN reference (RFC2822 is the string format at the start of OP's question)

And thus the conclusion can be made, that the use of the language "implementation dependent" everywhere in the specs is deliberately ambiguous, deferring to browser developers choices, but maintaining that it is not normative.

You can probably get away with using it, like object map key order can be used, but it is important to make the distinction that it is not by spec and eg moment.js chose to reject it most likely for this very reason.

OP tried to build his own ISO date string, which FF could not read, because he was using the wrong suffix. He probably could have gotten by with validating his string and using:

datestring +='+05:30'
instead of GMT+05:30 which makes the ISO string invalid.

Note for future readers. moment.js does have some issues and is not necessarily the best choice for everything related to Dates. You can most of the time get by with just normal Dates and using timestamp math, and you don't really need to bring in moment.js as a dependency.

However, as is shown in this thread, parsing of Dates can be problematic and allowing the built-in Date to parse your dates can cause unexpected results, especially because different platforms can give different results. Make sure you are fully aware of the subtle differences between platforms.

(Things like time zone differences, leap years, month day differences, string formatting (which is now mostly good enough with Intl.DateTimeFormat) are a few other reasons you should reach for a date library. Although moment(tz) does have subtle edge case bugs even in that regard.)

The date given at the top in the question is similar to the (string display representation) for Date format ratified in ES2015. Unfortunately, the month and day are not in the same order as the ratified standard, which contributed to additional problems when communicating with OP.

Using moment, moment.tz, and custom format

//var newdate = $(this).data("systemdate");//var format = $(this).data("format");
// shim newdate, format valuesnewdate=`Thu Oct 01 2020 05:30:00 GMT+0530 (India Standard Time)`format = `ddd MMM DD YYYY hh:mm:ss ZZ`
var timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;// other ways to get timezone. use the one that gets the right results:t=new Date().getTimezoneOffset()/60var timezone2 = `+${`${t|0}`.padStart(2,'0')}:${`${(t-(t|0))*60}`.padStart(2,'0')}`
console.log(moment.tz.guess(), timezone, timezone2)
// example custom format string using strict mode and isValid() for first example:var result = moment(newdate.replace(/ \(.*\)/,''),'ddd MMM DD YYYY HH:mm:ss [GMT]Z', true)if (result.isValid()) result = result.tz(timezone).format(format)else; //didn't match, continue to try to parse date string with other methods here
console.log(result);
newdate=`2020-11-01 05:30:00`
// this works, but is not recommended:// should use strict mode to make sure you recognize the format// and you want to force time zone parsing in your desired time zonevar result = moment.tz(newdate, 'Asia/Calcutta').tz(timezone).format(format);console.log(result);
// notice 3rd parameter is true for strict mode. reject dates that don't matchvar result = moment.tz(newdate, 'YYYY-MM-DD HH:mm:ss', true, 'Asia/Calcutta')if (result.isValid()) result = result.tz(timezone).format(format)else; // try to fallback to parsing date other waysconsole.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.3/moment-with-locales.min.js" integrity="sha256-8d6kI5cQEwofkZmaPTRbKgyD70GN5mDpTYNP9YWhTlI=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.28/moment-timezone-with-data.js" integrity="sha256-O1PdKrSbpAYWSBteb7yX/CMmHhu3US31mtCbsryGwaY=" crossorigin="anonymous"></script>


Related Topics



Leave a reply



Submit