moment.js is great but sometimes you don't want to pull a large number of dependencies for simple things.
The following works as well:
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
console.log(localISOTime) // => '2015-01-26T06:40:36.181'
The slice(0, -1) gets rid of the trailing Z which represents Zulu timezone and can be replaced by your own.
moment.js is great but sometimes you don't want to pull a large number of dependencies for simple things.
The following works as well:
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
console.log(localISOTime) // => '2015-01-26T06:40:36.181'
The slice(0, -1) gets rid of the trailing Z which represents Zulu timezone and can be replaced by your own.
My solution without using moment is to convert it to a timestamp, add the timezone offset, then convert back to a date object, and then run the toISOString()
var date = new Date(); // Or the date you'd like converted.
var isoDateTime = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
Why .toISOString() gives different time?
Date object and timezones stuff
formatISO doesn't use UTC (Z) timezone
I do I get Local time using Date().toISOstring() - Programming & Development - Spiceworks Community
The toISOString() method always outputs the time in UTC. From the docs:
The timezone is always zero UTC offset, as denoted by the suffix "Z".
In this case, the date is still the 22nd in UTC but, in your timezone, it's already the 23rd.
The Date object you have here is still in your local timezone, though. It just happens that the toISOString() method always outputs a UTC representation. If you do the following, you should see the date you're expecting:
console.log(new Date().toLocaleString()) // "1/22/2019, 3:14:18 PM" for me (US Pacific Time)
toISOString() returns a date/time in ISO format with timezone as UTC +0.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
when I set a date using a calander libary and save it in my localstorage as date.toISOString().split("T")[0] and after reloading the page, I retrieve from the localstorage and set in my local variable with new Date(date), it sets the time 1 day backward. I'm guessing its because the timezone i'm using is US and since US is 7 hours behind UTC, so new Date() treats the argument as a UTC time and converts it into a local time?, how do I configure it to give me the exact date I stored in my localstorage?