Convert JS date time to MySQL datetime - javascript

Does anyone know how to convert JS dateTime to MySQL datetime? Also is there a way to add a specific number of minutes to JS datetime and then pass it to MySQL datetime?

var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
('00' + date.getUTCDate()).slice(-2) + ' ' +
('00' + date.getUTCHours()).slice(-2) + ':' +
('00' + date.getUTCMinutes()).slice(-2) + ':' +
('00' + date.getUTCSeconds()).slice(-2);
console.log(date);
or even shorter:
new Date().toISOString().slice(0, 19).replace('T', ' ');
Output:
2012-06-22 05:40:06
For more advanced use cases, including controlling the timezone, consider using http://momentjs.com/:
require('moment')().format('YYYY-MM-DD HH:mm:ss');
For a lightweight alternative to momentjs, consider https://github.com/taylorhakes/fecha
require('fecha').format('YYYY-MM-DD HH:mm:ss')

I think the solution can be less clunky by using method toISOString(), it has a wide browser compatibility.
So your expression will be a one-liner:
new Date().toISOString().slice(0, 19).replace('T', ' ');
The generated output:
"2017-06-29 17:54:04"

While JS does possess enough basic tools to do this, it's pretty clunky.
/**
* You first need to create a formatting function to pad numbers to two digits…
**/
function twoDigits(d) {
if(0 <= d && d < 10) return "0" + d.toString();
if(-10 < d && d < 0) return "-0" + (-1*d).toString();
return d.toString();
}
/**
* …and then create the method to output the date string as desired.
* Some people hate using prototypes this way, but if you are going
* to apply this to more than one Date object, having it as a prototype
* makes sense.
**/
Date.prototype.toMysqlFormat = function() {
return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};

JS time value for MySQL
var datetime = new Date().toLocaleString();
OR
const DATE_FORMATER = require( 'dateformat' );
var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );
OR
const MOMENT= require( 'moment' );
let datetime = MOMENT().format( 'YYYY-MM-DD HH:mm:ss.000' );
you can send this in params its will work.

For arbitrary date string,
// Your default date object
var starttime = new Date();
// Get the iso time (GMT 0 == UTC 0)
var isotime = new Date((new Date(starttime)).toISOString() );
// getTime() is the unix time value, in milliseconds.
// getTimezoneOffset() is UTC time and local time in minutes.
// 60000 = 60*1000 converts getTimezoneOffset() from minutes to milliseconds.
var fixedtime = new Date(isotime.getTime()-(starttime.getTimezoneOffset()*60000));
// toISOString() is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ.
// .slice(0, 19) removes the last 5 chars, ".sssZ",which is (UTC offset).
// .replace('T', ' ') removes the pad between the date and time.
var formatedMysqlString = fixedtime.toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );
Or a single line solution,
var formatedMysqlString = (new Date ((new Date((new Date(new Date())).toISOString() )).getTime() - ((new Date()).getTimezoneOffset()*60000))).toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );
This solution also works for Node.js when using Timestamp in mysql.
#Gajus Kuizinas's first answer seems to modify mozilla's toISOString prototype

new Date().toISOString().slice(0, 10)+" "+new Date().toLocaleTimeString('en-GB');

The easiest correct way to convert JS Date to SQL datetime format that occur to me is this one. It correctly handles timezone offset.
const toSqlDatetime = (inputDate) => {
const date = new Date(inputDate)
const dateWithOffest = new Date(date.getTime() - (date.getTimezoneOffset() * 60000))
return dateWithOffest
.toISOString()
.slice(0, 19)
.replace('T', ' ')
}
toSqlDatetime(new Date()) // 2019-08-07 11:58:57
toSqlDatetime(new Date('2016-6-23 1:54:16')) // 2016-06-23 01:54:16
Beware that #Paulo Roberto answer will produce incorrect results at the turn on new day (i can't leave comments). For example:
var d = new Date('2016-6-23 1:54:16'),
finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
console.log(finalDate); // 2016-06-22 01:54:16
We've got 22 June instead of 23!

The venerable DateJS library has a formatting routine (it overrides ".toString()"). You could also do one yourself pretty easily because the "Date" methods give you all the numbers you need.

The short version:
// JavaScript timestamps need to be converted to UTC time to match MySQL
// MySQL formatted UTC timestamp +30 minutes
let d = new Date()
let mySqlTimestamp = new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
(d.getMinutes() + 30), // add 30 minutes
d.getSeconds(),
d.getMilliseconds()
).toISOString().slice(0, 19).replace('T', ' ')
console.log("MySQL formatted UTC timestamp: " + mySqlTimestamp)
UTC time is generally the best option for storing timestamps in MySQL. If you don't have root access, then run set time_zone = '+00:00' at the start of your connection.
Display a timestamp in a specific time zone in MySQL with the method convert_tz.
select convert_tz(now(), 'SYSTEM', 'America/Los_Angeles');
JavaScript timestamps are based on your device's clock and include the time zone. Before sending any timestamps generated from JavaScript, you should convert them to UTC time. JavaScript has a method called toISOString() which formats a JavaScript timestamp to look similar to MySQL timestamp and converts the timestamp to UTC time. The final cleanup takes place with slice and replace.
let timestmap = new Date()
timestmap.toISOString().slice(0, 19).replace('T', ' ')
Long version to show what is happening:
// JavaScript timestamps need to be converted to UTC time to match MySQL
// local timezone provided by user's device
let d = new Date()
console.log("JavaScript timestamp: " + d.toLocaleString())
// add 30 minutes
let add30Minutes = new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
(d.getMinutes() + 30), // add 30 minutes
d.getSeconds(),
d.getMilliseconds()
)
console.log("Add 30 mins: " + add30Minutes.toLocaleString())
// ISO formatted UTC timestamp
// timezone is always zero UTC offset, as denoted by the suffix "Z"
let isoString = add30Minutes.toISOString()
console.log("ISO formatted UTC timestamp: " + isoString)
// MySQL formatted UTC timestamp: YYYY-MM-DD HH:MM:SS
let mySqlTimestamp = isoString.slice(0, 19).replace('T', ' ')
console.log("MySQL formatted UTC timestamp: " + mySqlTimestamp)

This is by far the easiest way I can think of
new Date().toISOString().slice(0, 19).replace("T", " ")

Full workaround (to mantain the timezone) using #Gajus answer concept:
var d = new Date(),
finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
console.log(finalDate); //2018-09-28 16:19:34 --example output

I have given simple JavaScript date format examples please check the bellow code
var data = new Date($.now()); // without jquery remove this $.now()
console.log(data)// Thu Jun 23 2016 15:48:24 GMT+0530 (IST)
var d = new Date,
dformat = [d.getFullYear() ,d.getMonth()+1,
d.getDate()
].join('-')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
console.log(dformat) //2016-6-23 15:54:16
Using momentjs
var date = moment().format('YYYY-MM-DD H:mm:ss');
console.log(date) // 2016-06-23 15:59:08
Example please check https://jsfiddle.net/sjy3vjwm/2/

var _t = new Date();
if you want UTC format simply
_t.toLocaleString('indian', { timeZone: 'UTC' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
or
_t.toISOString().slice(0, 19).replace('T', ' ');
and if want in specific timezone then
_t.toLocaleString('indian', { timeZone: 'asia/kolkata' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');

Using toJSON() date function as below:
var sqlDatetime = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60 * 1000).toJSON().slice(0, 19).replace('T', ' ');
console.log(sqlDatetime);

Datetime in a different time zone
This uses #Gayus solution using the format outputted from toISOString() but it adjusts the minutes to account for the time zone.
Final format: 2022-03-01 13:32:51
let ts = new Date();
ts.setMinutes(ts.getMinutes() - ts.getTimezoneOffset());
console.log(ts.toISOString().slice(0, 19).replace('T', ' '));

I am surprised that no one mention the Swedish date time format for javascript yet.
the BCP 47 language tag for the Swedish language is sv-SE that you can use for the new Date "locale" parameter.
I am not saying it is a good practice, but it works.
console.log(new Date().toLocaleString([['sv-SE']])) //2022-09-10 17:02:39

A simple solution is send a timestamp to MySQL and let it do the conversion. Javascript uses timestamps in milliseconds whereas MySQL expects them to be in seconds - so a division by 1000 is needed:
// Current date / time as a timestamp:
let jsTimestamp = Date.now();
// **OR** a specific date / time as a timestamp:
jsTimestamp = new Date("2020-11-17 16:34:59").getTime();
// Adding 30 minutes (to answer the second part of the question):
jsTimestamp += 30 * 1000;
// Example query converting Javascript timestamp into a MySQL date
let sql = 'SELECT FROM_UNIXTIME(' + jsTimestamp + ' / 1000) AS mysql_date_time';

I needed a function to return the sql timestamp format in javascript form a selective timezone
<script>
console.log(getTimestamp("Europe/Amsterdam")); // Europe/Amsterdam
console.log(getTimestamp()); // UTC
function getTimestamp(timezone) {
if (timezone) {
var dateObject = new Date().toLocaleString("nl-NL", { // it will parse with the timeZone element, not this one
timeZone: timezone, // timezone eg "Europe/Amsterdam" or "UTC"
month: "2-digit",
day: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
let [dateRaw, timeRaw] = dateObject.split(" ");
let [day, month, year] = dateRaw.split("-");
var timestamp = year + "-" + month + "-" + day + " " + timeRaw;
}else{
// UTC from #Gajus, 95% faster then the above
timestamp = new Date().toISOString().slice(0, 19).replace("T", " ");
}
return timestamp; // YYYY-MM-DD HH:MI:SS
}
</script>

If you are using Date-fns then the functionality can be achived easily using format function.
const format = require("date-fns/format");
const date = new Date();
const formattedDate = format(date, "yyyy-MM-dd HH:mm:ss")

This is the easiest way -
new Date().toISOString().slice(0, 19).replace("T", " ")

I'm using this long time and it's very helpful for me, use as you like
Date.prototype.date=function() {
return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')
}
Date.prototype.time=function() {
return String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}
Date.prototype.dateTime=function() {
return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')+' '+String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
}
Date.prototype.addTime=function(time) {
var time=time.split(":")
var rd=new Date(this.setHours(this.getHours()+parseInt(time[0])))
rd=new Date(rd.setMinutes(rd.getMinutes()+parseInt(time[1])))
return new Date(rd.setSeconds(rd.getSeconds()+parseInt(time[2])))
}
Date.prototype.addDate=function(time) {
var time=time.split("-")
var rd=new Date(this.setFullYear(this.getFullYear()+parseInt(time[0])))
rd=new Date(rd.setMonth(rd.getMonth()+parseInt(time[1])))
return new Date(rd.setDate(rd.getDate()+parseInt(time[2])))
}
Date.prototype.subDate=function(time) {
var time=time.split("-")
var rd=new Date(this.setFullYear(this.getFullYear()-parseInt(time[0])))
rd=new Date(rd.setMonth(rd.getMonth()-parseInt(time[1])))
return new Date(rd.setDate(rd.getDate()-parseInt(time[2])))
}
and then just:
new Date().date()
which returns current date in 'MySQL format'
for add time is
new Date().addTime('0:30:0')
which will add 30 minutes.... and so on

Solution built on the basis of other answers, while maintaining the timezone and leading zeros:
var d = new Date;
var date = [
d.getFullYear(),
('00' + d.getMonth() + 1).slice(-2),
('00' + d.getDate() + 1).slice(-2)
].join('-');
var time = [
('00' + d.getHours()).slice(-2),
('00' + d.getMinutes()).slice(-2),
('00' + d.getSeconds()).slice(-2)
].join(':');
var dateTime = date + ' ' + time;
console.log(dateTime) // 2021-01-41 13:06:01

Simple: just Replace the T.
Format that I have from my <input class="form-control" type="datetime-local" is :
"2021-02-10T18:18"
So just replace the T, and it would look like this: "2021-02-10 18:18" SQL will eat that.
Here is my function:
var CreatedTime = document.getElementById("example-datetime-local-input").value;
var newTime = CreatedTime.replace("T", " ");
Reference:
https://www.tutorialrepublic.com/faq/how-to-replace-character-inside-a-string-in-javascript.php#:~:text=Answer%3A%20Use%20the%20JavaScript%20replace,the%20global%20(%20g%20)%20modifier.
https://www.tutorialrepublic.com/codelab.php?topic=faq&file=javascript-replace-character-in-a-string

Related

JavaScript get this month's 1st date [duplicate]

Goal: Find the local time and UTC time offset then construct the URL in following format.
Example URL: /Actions/Sleep?duration=2002-10-10T12:00:00−05:00
The format is based on the W3C recommendation. The documentation says:
For example, 2002-10-10T12:00:00−05:00 (noon on 10 October 2002,
Central Daylight Savings Time as well as Eastern Standard Time in the U.S.)
is equal to 2002-10-10T17:00:00Z, five hours later than 2002-10-10T12:00:00Z.
So based on my understanding, I need to find my local time by new Date() then use getTimezoneOffset() function to compute the difference then attach it to the end of string.
Get local time with format
var local = new Date().format("yyyy-MM-ddThh:mm:ss"); // 2013-07-02T09:00:00
Get UTC time offset by hour
var offset = local.getTimezoneOffset() / 60; // 7
Construct URL (time part only)
var duration = local + "-" + offset + ":00"; // 2013-07-02T09:00:00-7:00
The above output means my local time is 2013/07/02 9am and difference from UTC is 7 hours (UTC is 7 hours ahead of local time)
So far it seems to work but what if getTimezoneOffset() returns negative value like -120?
I'm wondering how the format should look like in such case because I cannot figure out from W3C documentation.
Here's a simple helper function that will format JS dates for you.
function toIsoString(date) {
var tzo = -date.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
return (num < 10 ? '0' : '') + num;
};
return date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
dif + pad(Math.floor(Math.abs(tzo) / 60)) +
':' + pad(Math.abs(tzo) % 60);
}
var dt = new Date();
console.log(toIsoString(dt));
getTimezoneOffset() returns the opposite sign of the format required by the spec that you referenced.
This format is also known as ISO8601, or more precisely as RFC3339.
In this format, UTC is represented with a Z while all other formats are represented by an offset from UTC. The meaning is the same as JavaScript's, but the order of subtraction is inverted, so the result carries the opposite sign.
Also, there is no method on the native Date object called format, so your function in #1 will fail unless you are using a library to achieve this. Refer to this documentation.
If you are seeking a library that can work with this format directly, I recommend trying moment.js. In fact, this is the default format, so you can simply do this:
var m = moment(); // get "now" as a moment
var s = m.format(); // the ISO format is the default so no parameters are needed
// sample output: 2013-07-01T17:55:13-07:00
This is a well-tested, cross-browser solution, and has many other useful features.
I think it is worth considering that you can get the requested info with just a single API call to the standard library...
new Date().toLocaleString( 'sv', { timeZoneName: 'short' } );
// produces "2019-10-30 15:33:47 GMT−4"
You would have to do text swapping if you want to add the 'T' delimiter, remove the 'GMT-', or append the ':00' to the end.
But then you can easily play with the other options if you want to eg. use 12h time or omit the seconds etc.
Note that I'm using Sweden as locale because it is one of the countries that uses ISO 8601 format. I think most of the ISO countries use this 'GMT-4' format for the timezone offset other then Canada which uses the time zone abbreviation eg. "EDT" for eastern-daylight-time.
You can get the same thing from the newer standard i18n function "Intl.DateTimeFormat()"
but you have to tell it to include the time via the options or it will just give date.
My answer is a slight variation for those who just want today's date in the local timezone in the YYYY-MM-DD format.
Let me be clear:
My Goal: get today's date in the user's timezone but formatted as ISO8601 (YYYY-MM-DD)
Here is the code:
new Date().toLocaleDateString("sv") // "2020-02-23" //
This works because the Sweden locale uses the ISO 8601 format.
This is my function for the clients timezone, it's lite weight and simple
function getCurrentDateTimeMySql() {
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, 19).replace('T', ' ');
var mySqlDT = localISOTime;
return mySqlDT;
}
Check this:
function dateToLocalISO(date) {
const off = date.getTimezoneOffset()
const absoff = Math.abs(off)
return (new Date(date.getTime() - off*60*1000).toISOString().substr(0,23) +
(off > 0 ? '-' : '+') +
Math.floor(absoff / 60).toFixed(0).padStart(2,'0') + ':' +
(absoff % 60).toString().padStart(2,'0'))
}
// Test it:
d = new Date()
dateToLocalISO(d)
// ==> '2019-06-21T16:07:22.181-03:00'
// Is similar to:
moment = require('moment')
moment(d).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
// ==> '2019-06-21T16:07:22.181-03:00'
You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.
Date.prototype.getISOTimezoneOffset = function () {
const offset = this.getTimezoneOffset();
return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
}
Date.prototype.toISOLocaleString = function () {
return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
this.getMilliseconds().leftPad(3);
}
Number.prototype.leftPad = function (size) {
var s = String(this);
while (s.length < (size || 2)) {
s = "0" + s;
}
return s;
}
Example usage:
var date = new Date();
console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
// Prints "2020-08-05T16:15:46.525+10:00"
I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.
(The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString for anyone without said library.)
Just my two cents here
I was facing this issue with datetimes so what I did is this:
const moment = require('moment-timezone')
const date = moment.tz('America/Bogota').format()
Then save date to db to be able to compare it from some query.
To install moment-timezone
npm i moment-timezone
No moment.js needed: Here's a full round trip answer, from an input type of "datetime-local" which outputs an ISOLocal string to UTCseconds at GMT and back:
<input type="datetime-local" value="2020-02-16T19:30">
isoLocal="2020-02-16T19:30"
utcSeconds=new Date(isoLocal).getTime()/1000
//here you have 1581899400 for utcSeconds
let isoLocal=new Date(utcSeconds*1000-new Date().getTimezoneOffset()*60000).toISOString().substring(0,16)
2020-02-16T19:30
date to ISO string,
with local(computer) time zone,
with or without milliseconds
ISO ref: https://en.wikipedia.org/wiki/ISO_8601
how to use: toIsoLocalTime(new Date())
function toIsoLocalTime(value) {
if (value instanceof Date === false)
value = new Date();
const off = value.getTimezoneOffset() * -1;
const del = value.getMilliseconds() ? 'Z' : '.'; // have milliseconds ?
value = new Date(value.getTime() + off * 60000); // add or subtract time zone
return value
.toISOString()
.split(del)[0]
+ (off < 0 ? '-' : '+')
+ ('0' + Math.abs(Math.floor(off / 60))).substr(-2)
+ ':'
+ ('0' + Math.abs(off % 60)).substr(-2);
}
function test(value) {
const event = new Date(value);
console.info(value + ' -> ' + toIsoLocalTime(event) + ', test = ' + (event.getTime() === (new Date(toIsoLocalTime(event))).getTime() ));
}
test('2017-06-14T10:00:00+03:00'); // test with timezone
test('2017-06-14T10:00:00'); // test with local timezone
test('2017-06-14T10:00:00Z'); // test with UTC format
test('2099-12-31T23:59:59.999Z'); // date with milliseconds
test((new Date()).toString()); // now
consider using moment (like Matt's answer).
From version 2.20.0, you may call .toISOString(true) to prevent UTC conversion:
console.log(moment().toISOString(true));
// sample output: 2022-04-06T16:26:36.758+03:00
Use Temporal.
Temporal.Now.zonedDateTimeISO().toString()
// '2022-08-09T14:16:47.762797591-07:00[America/Los_Angeles]'
To omit the fractional seconds and IANA time zone:
Temporal.Now.zonedDateTimeISO().toString({
timeZoneName: "never",
fractionalSecondDigits: 0
})
// '2022-08-09T14:18:34-07:00'
Note: Temporal is currently (2022) available as a polyfill, but will soon be available in major browsers.
With luxon:
DateTime.now().toISODate() // 2022-05-23
Here are the functions I used for this end:
function localToGMTStingTime(localTime = null) {
var date = localTime ? new Date(localTime) : new Date();
return new Date(date.getTime() + (date.getTimezoneOffset() * 60000)).toISOString();
};
function GMTToLocalStingTime(GMTTime = null) {
var date = GMTTime ? new Date(GMTTime) : new Date();;
return new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
};
let myDate = new Date(dateToBeFormatted * 1000); // depends if you have milliseconds, or seconds, then the * 1000 might be not, or required.
timeOffset = myDate.getTimezoneOffset();
myDate = new Date(myDate.getTime() - (timeOffset * 60 * 1000));
console.log(myDate.toISOString().split('T')[0]);
Inspired by https://stackoverflow.com/a/29774197/11127383, including timezone offset comment.
a simple way to get:
//using a sample date
let iso_str = '2022-06-11T01:51:59.618Z';
let d = new Date(iso_str);
let tz = 'America/Santiago'
let options = {
timeZone:tz ,
timeZoneName:'longOffset',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
fractionalSecondDigits: 3
}
str_locale = d.toLocaleString("sv-SE",options);
iso_str_tz = str_locale.replace(/(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2}),(\d+)\s+/,'$1-$2-$3T$4:$5:$6.$7').replace('GMT−', '-' ).replace('GMT+','+')
console.log('iso_str : ',iso_str);
console.log('str_locale : ',str_locale);
console.log('iso_str_tz : ',iso_str_tz);
console.log('iso_str_tz --> date : ',new Date(iso_str_tz));
console.log('iso_str_tz --> iso_str: ',new Date(iso_str_tz).toISOString());
Using moment.js, you can use keepOffset parameter of toISOString:
toISOString(keepOffset?: boolean): string;
moment().toISOString(true)
Alternative approach with dayjs
import dayjs from "dayjs"
const formattedDateTime = dayjs(new Date()).format()
console.log(formattedDateTime) // Prints 2022-11-09T07:49:29+03:00
Here's another way a convert your date with an offset.
function toCustomDateString(date, offset) {
function pad(number) {
if (number < 10) {
return "0" + number;
}
return number;
}
var offsetHours = offset / 60;
var offsetMinutes = offset % 60;
var sign = (offset > 0) ? "+" : "-";
offsetHours = pad(Math.floor(Math.abs(offsetHours)));
offsetMinutes = pad(Math.abs(offsetMinutes));
return date.getFullYear() +
"-" + pad(date.getMonth() + 1) +
"-" + pad(date.getDate()) +
"T" + pad(date.getHours()) +
":" + pad(date.getMinutes()) +
":" + pad(date.getSeconds()) +
sign + offsetHours +
":" + offsetMinutes;
}
Then you can use it like this:
var date = new Date();
var offset = 330; // offset in minutes from UTC, for India it is 330 minutes ahead of UTC
var customDateString = toCustomDateString(date, offset);
console.log(customDateString);
// Output: "2023-02-09T10:29:31+05:30"
function setDate(){
var now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
var timeToSet = now.toISOString().slice(0,16);
/*
If you have an element called "eventDate" like the following:
<input type="datetime-local" name="eventdate" id="eventdate" />
and you would like to set the current and minimum time then use the following:
*/
var elem = document.getElementById("eventDate");
elem.value = timeToSet;
elem.min = timeToSet;
}
I found another more easy solution:
let now = new Date();
// correct time zone offset for generating iso string
now.setMinutes(now.getMinutes() - now.getTimezoneOffset())
now = now.toISOString();
I undo the timezone offset by substracting it from the current date object.
The UTC time from the date object is now pointing to the local time.
That gives you the possibility to get the iso date for the local time.

Get the hour shown in an ISOstring with an offset [duplicate]

Goal: Find the local time and UTC time offset then construct the URL in following format.
Example URL: /Actions/Sleep?duration=2002-10-10T12:00:00−05:00
The format is based on the W3C recommendation. The documentation says:
For example, 2002-10-10T12:00:00−05:00 (noon on 10 October 2002,
Central Daylight Savings Time as well as Eastern Standard Time in the U.S.)
is equal to 2002-10-10T17:00:00Z, five hours later than 2002-10-10T12:00:00Z.
So based on my understanding, I need to find my local time by new Date() then use getTimezoneOffset() function to compute the difference then attach it to the end of string.
Get local time with format
var local = new Date().format("yyyy-MM-ddThh:mm:ss"); // 2013-07-02T09:00:00
Get UTC time offset by hour
var offset = local.getTimezoneOffset() / 60; // 7
Construct URL (time part only)
var duration = local + "-" + offset + ":00"; // 2013-07-02T09:00:00-7:00
The above output means my local time is 2013/07/02 9am and difference from UTC is 7 hours (UTC is 7 hours ahead of local time)
So far it seems to work but what if getTimezoneOffset() returns negative value like -120?
I'm wondering how the format should look like in such case because I cannot figure out from W3C documentation.
Here's a simple helper function that will format JS dates for you.
function toIsoString(date) {
var tzo = -date.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
return (num < 10 ? '0' : '') + num;
};
return date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
dif + pad(Math.floor(Math.abs(tzo) / 60)) +
':' + pad(Math.abs(tzo) % 60);
}
var dt = new Date();
console.log(toIsoString(dt));
getTimezoneOffset() returns the opposite sign of the format required by the spec that you referenced.
This format is also known as ISO8601, or more precisely as RFC3339.
In this format, UTC is represented with a Z while all other formats are represented by an offset from UTC. The meaning is the same as JavaScript's, but the order of subtraction is inverted, so the result carries the opposite sign.
Also, there is no method on the native Date object called format, so your function in #1 will fail unless you are using a library to achieve this. Refer to this documentation.
If you are seeking a library that can work with this format directly, I recommend trying moment.js. In fact, this is the default format, so you can simply do this:
var m = moment(); // get "now" as a moment
var s = m.format(); // the ISO format is the default so no parameters are needed
// sample output: 2013-07-01T17:55:13-07:00
This is a well-tested, cross-browser solution, and has many other useful features.
I think it is worth considering that you can get the requested info with just a single API call to the standard library...
new Date().toLocaleString( 'sv', { timeZoneName: 'short' } );
// produces "2019-10-30 15:33:47 GMT−4"
You would have to do text swapping if you want to add the 'T' delimiter, remove the 'GMT-', or append the ':00' to the end.
But then you can easily play with the other options if you want to eg. use 12h time or omit the seconds etc.
Note that I'm using Sweden as locale because it is one of the countries that uses ISO 8601 format. I think most of the ISO countries use this 'GMT-4' format for the timezone offset other then Canada which uses the time zone abbreviation eg. "EDT" for eastern-daylight-time.
You can get the same thing from the newer standard i18n function "Intl.DateTimeFormat()"
but you have to tell it to include the time via the options or it will just give date.
My answer is a slight variation for those who just want today's date in the local timezone in the YYYY-MM-DD format.
Let me be clear:
My Goal: get today's date in the user's timezone but formatted as ISO8601 (YYYY-MM-DD)
Here is the code:
new Date().toLocaleDateString("sv") // "2020-02-23" //
This works because the Sweden locale uses the ISO 8601 format.
This is my function for the clients timezone, it's lite weight and simple
function getCurrentDateTimeMySql() {
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, 19).replace('T', ' ');
var mySqlDT = localISOTime;
return mySqlDT;
}
Check this:
function dateToLocalISO(date) {
const off = date.getTimezoneOffset()
const absoff = Math.abs(off)
return (new Date(date.getTime() - off*60*1000).toISOString().substr(0,23) +
(off > 0 ? '-' : '+') +
Math.floor(absoff / 60).toFixed(0).padStart(2,'0') + ':' +
(absoff % 60).toString().padStart(2,'0'))
}
// Test it:
d = new Date()
dateToLocalISO(d)
// ==> '2019-06-21T16:07:22.181-03:00'
// Is similar to:
moment = require('moment')
moment(d).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
// ==> '2019-06-21T16:07:22.181-03:00'
You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.
Date.prototype.getISOTimezoneOffset = function () {
const offset = this.getTimezoneOffset();
return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
}
Date.prototype.toISOLocaleString = function () {
return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
this.getMilliseconds().leftPad(3);
}
Number.prototype.leftPad = function (size) {
var s = String(this);
while (s.length < (size || 2)) {
s = "0" + s;
}
return s;
}
Example usage:
var date = new Date();
console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
// Prints "2020-08-05T16:15:46.525+10:00"
I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.
(The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString for anyone without said library.)
Just my two cents here
I was facing this issue with datetimes so what I did is this:
const moment = require('moment-timezone')
const date = moment.tz('America/Bogota').format()
Then save date to db to be able to compare it from some query.
To install moment-timezone
npm i moment-timezone
No moment.js needed: Here's a full round trip answer, from an input type of "datetime-local" which outputs an ISOLocal string to UTCseconds at GMT and back:
<input type="datetime-local" value="2020-02-16T19:30">
isoLocal="2020-02-16T19:30"
utcSeconds=new Date(isoLocal).getTime()/1000
//here you have 1581899400 for utcSeconds
let isoLocal=new Date(utcSeconds*1000-new Date().getTimezoneOffset()*60000).toISOString().substring(0,16)
2020-02-16T19:30
date to ISO string,
with local(computer) time zone,
with or without milliseconds
ISO ref: https://en.wikipedia.org/wiki/ISO_8601
how to use: toIsoLocalTime(new Date())
function toIsoLocalTime(value) {
if (value instanceof Date === false)
value = new Date();
const off = value.getTimezoneOffset() * -1;
const del = value.getMilliseconds() ? 'Z' : '.'; // have milliseconds ?
value = new Date(value.getTime() + off * 60000); // add or subtract time zone
return value
.toISOString()
.split(del)[0]
+ (off < 0 ? '-' : '+')
+ ('0' + Math.abs(Math.floor(off / 60))).substr(-2)
+ ':'
+ ('0' + Math.abs(off % 60)).substr(-2);
}
function test(value) {
const event = new Date(value);
console.info(value + ' -> ' + toIsoLocalTime(event) + ', test = ' + (event.getTime() === (new Date(toIsoLocalTime(event))).getTime() ));
}
test('2017-06-14T10:00:00+03:00'); // test with timezone
test('2017-06-14T10:00:00'); // test with local timezone
test('2017-06-14T10:00:00Z'); // test with UTC format
test('2099-12-31T23:59:59.999Z'); // date with milliseconds
test((new Date()).toString()); // now
consider using moment (like Matt's answer).
From version 2.20.0, you may call .toISOString(true) to prevent UTC conversion:
console.log(moment().toISOString(true));
// sample output: 2022-04-06T16:26:36.758+03:00
Use Temporal.
Temporal.Now.zonedDateTimeISO().toString()
// '2022-08-09T14:16:47.762797591-07:00[America/Los_Angeles]'
To omit the fractional seconds and IANA time zone:
Temporal.Now.zonedDateTimeISO().toString({
timeZoneName: "never",
fractionalSecondDigits: 0
})
// '2022-08-09T14:18:34-07:00'
Note: Temporal is currently (2022) available as a polyfill, but will soon be available in major browsers.
With luxon:
DateTime.now().toISODate() // 2022-05-23
Here are the functions I used for this end:
function localToGMTStingTime(localTime = null) {
var date = localTime ? new Date(localTime) : new Date();
return new Date(date.getTime() + (date.getTimezoneOffset() * 60000)).toISOString();
};
function GMTToLocalStingTime(GMTTime = null) {
var date = GMTTime ? new Date(GMTTime) : new Date();;
return new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
};
let myDate = new Date(dateToBeFormatted * 1000); // depends if you have milliseconds, or seconds, then the * 1000 might be not, or required.
timeOffset = myDate.getTimezoneOffset();
myDate = new Date(myDate.getTime() - (timeOffset * 60 * 1000));
console.log(myDate.toISOString().split('T')[0]);
Inspired by https://stackoverflow.com/a/29774197/11127383, including timezone offset comment.
a simple way to get:
//using a sample date
let iso_str = '2022-06-11T01:51:59.618Z';
let d = new Date(iso_str);
let tz = 'America/Santiago'
let options = {
timeZone:tz ,
timeZoneName:'longOffset',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
fractionalSecondDigits: 3
}
str_locale = d.toLocaleString("sv-SE",options);
iso_str_tz = str_locale.replace(/(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2}),(\d+)\s+/,'$1-$2-$3T$4:$5:$6.$7').replace('GMT−', '-' ).replace('GMT+','+')
console.log('iso_str : ',iso_str);
console.log('str_locale : ',str_locale);
console.log('iso_str_tz : ',iso_str_tz);
console.log('iso_str_tz --> date : ',new Date(iso_str_tz));
console.log('iso_str_tz --> iso_str: ',new Date(iso_str_tz).toISOString());
Using moment.js, you can use keepOffset parameter of toISOString:
toISOString(keepOffset?: boolean): string;
moment().toISOString(true)
Alternative approach with dayjs
import dayjs from "dayjs"
const formattedDateTime = dayjs(new Date()).format()
console.log(formattedDateTime) // Prints 2022-11-09T07:49:29+03:00
Here's another way a convert your date with an offset.
function toCustomDateString(date, offset) {
function pad(number) {
if (number < 10) {
return "0" + number;
}
return number;
}
var offsetHours = offset / 60;
var offsetMinutes = offset % 60;
var sign = (offset > 0) ? "+" : "-";
offsetHours = pad(Math.floor(Math.abs(offsetHours)));
offsetMinutes = pad(Math.abs(offsetMinutes));
return date.getFullYear() +
"-" + pad(date.getMonth() + 1) +
"-" + pad(date.getDate()) +
"T" + pad(date.getHours()) +
":" + pad(date.getMinutes()) +
":" + pad(date.getSeconds()) +
sign + offsetHours +
":" + offsetMinutes;
}
Then you can use it like this:
var date = new Date();
var offset = 330; // offset in minutes from UTC, for India it is 330 minutes ahead of UTC
var customDateString = toCustomDateString(date, offset);
console.log(customDateString);
// Output: "2023-02-09T10:29:31+05:30"
function setDate(){
var now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
var timeToSet = now.toISOString().slice(0,16);
/*
If you have an element called "eventDate" like the following:
<input type="datetime-local" name="eventdate" id="eventdate" />
and you would like to set the current and minimum time then use the following:
*/
var elem = document.getElementById("eventDate");
elem.value = timeToSet;
elem.min = timeToSet;
}
I found another more easy solution:
let now = new Date();
// correct time zone offset for generating iso string
now.setMinutes(now.getMinutes() - now.getTimezoneOffset())
now = now.toISOString();
I undo the timezone offset by substracting it from the current date object.
The UTC time from the date object is now pointing to the local time.
That gives you the possibility to get the iso date for the local time.

How to pass datetime from client(browser) to server [duplicate]

Goal: Find the local time and UTC time offset then construct the URL in following format.
Example URL: /Actions/Sleep?duration=2002-10-10T12:00:00−05:00
The format is based on the W3C recommendation. The documentation says:
For example, 2002-10-10T12:00:00−05:00 (noon on 10 October 2002,
Central Daylight Savings Time as well as Eastern Standard Time in the U.S.)
is equal to 2002-10-10T17:00:00Z, five hours later than 2002-10-10T12:00:00Z.
So based on my understanding, I need to find my local time by new Date() then use getTimezoneOffset() function to compute the difference then attach it to the end of string.
Get local time with format
var local = new Date().format("yyyy-MM-ddThh:mm:ss"); // 2013-07-02T09:00:00
Get UTC time offset by hour
var offset = local.getTimezoneOffset() / 60; // 7
Construct URL (time part only)
var duration = local + "-" + offset + ":00"; // 2013-07-02T09:00:00-7:00
The above output means my local time is 2013/07/02 9am and difference from UTC is 7 hours (UTC is 7 hours ahead of local time)
So far it seems to work but what if getTimezoneOffset() returns negative value like -120?
I'm wondering how the format should look like in such case because I cannot figure out from W3C documentation.
Here's a simple helper function that will format JS dates for you.
function toIsoString(date) {
var tzo = -date.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
return (num < 10 ? '0' : '') + num;
};
return date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
dif + pad(Math.floor(Math.abs(tzo) / 60)) +
':' + pad(Math.abs(tzo) % 60);
}
var dt = new Date();
console.log(toIsoString(dt));
getTimezoneOffset() returns the opposite sign of the format required by the spec that you referenced.
This format is also known as ISO8601, or more precisely as RFC3339.
In this format, UTC is represented with a Z while all other formats are represented by an offset from UTC. The meaning is the same as JavaScript's, but the order of subtraction is inverted, so the result carries the opposite sign.
Also, there is no method on the native Date object called format, so your function in #1 will fail unless you are using a library to achieve this. Refer to this documentation.
If you are seeking a library that can work with this format directly, I recommend trying moment.js. In fact, this is the default format, so you can simply do this:
var m = moment(); // get "now" as a moment
var s = m.format(); // the ISO format is the default so no parameters are needed
// sample output: 2013-07-01T17:55:13-07:00
This is a well-tested, cross-browser solution, and has many other useful features.
I think it is worth considering that you can get the requested info with just a single API call to the standard library...
new Date().toLocaleString( 'sv', { timeZoneName: 'short' } );
// produces "2019-10-30 15:33:47 GMT−4"
You would have to do text swapping if you want to add the 'T' delimiter, remove the 'GMT-', or append the ':00' to the end.
But then you can easily play with the other options if you want to eg. use 12h time or omit the seconds etc.
Note that I'm using Sweden as locale because it is one of the countries that uses ISO 8601 format. I think most of the ISO countries use this 'GMT-4' format for the timezone offset other then Canada which uses the time zone abbreviation eg. "EDT" for eastern-daylight-time.
You can get the same thing from the newer standard i18n function "Intl.DateTimeFormat()"
but you have to tell it to include the time via the options or it will just give date.
My answer is a slight variation for those who just want today's date in the local timezone in the YYYY-MM-DD format.
Let me be clear:
My Goal: get today's date in the user's timezone but formatted as ISO8601 (YYYY-MM-DD)
Here is the code:
new Date().toLocaleDateString("sv") // "2020-02-23" //
This works because the Sweden locale uses the ISO 8601 format.
This is my function for the clients timezone, it's lite weight and simple
function getCurrentDateTimeMySql() {
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, 19).replace('T', ' ');
var mySqlDT = localISOTime;
return mySqlDT;
}
Check this:
function dateToLocalISO(date) {
const off = date.getTimezoneOffset()
const absoff = Math.abs(off)
return (new Date(date.getTime() - off*60*1000).toISOString().substr(0,23) +
(off > 0 ? '-' : '+') +
Math.floor(absoff / 60).toFixed(0).padStart(2,'0') + ':' +
(absoff % 60).toString().padStart(2,'0'))
}
// Test it:
d = new Date()
dateToLocalISO(d)
// ==> '2019-06-21T16:07:22.181-03:00'
// Is similar to:
moment = require('moment')
moment(d).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
// ==> '2019-06-21T16:07:22.181-03:00'
You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.
Date.prototype.getISOTimezoneOffset = function () {
const offset = this.getTimezoneOffset();
return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
}
Date.prototype.toISOLocaleString = function () {
return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
this.getMilliseconds().leftPad(3);
}
Number.prototype.leftPad = function (size) {
var s = String(this);
while (s.length < (size || 2)) {
s = "0" + s;
}
return s;
}
Example usage:
var date = new Date();
console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
// Prints "2020-08-05T16:15:46.525+10:00"
I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.
(The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString for anyone without said library.)
Just my two cents here
I was facing this issue with datetimes so what I did is this:
const moment = require('moment-timezone')
const date = moment.tz('America/Bogota').format()
Then save date to db to be able to compare it from some query.
To install moment-timezone
npm i moment-timezone
No moment.js needed: Here's a full round trip answer, from an input type of "datetime-local" which outputs an ISOLocal string to UTCseconds at GMT and back:
<input type="datetime-local" value="2020-02-16T19:30">
isoLocal="2020-02-16T19:30"
utcSeconds=new Date(isoLocal).getTime()/1000
//here you have 1581899400 for utcSeconds
let isoLocal=new Date(utcSeconds*1000-new Date().getTimezoneOffset()*60000).toISOString().substring(0,16)
2020-02-16T19:30
date to ISO string,
with local(computer) time zone,
with or without milliseconds
ISO ref: https://en.wikipedia.org/wiki/ISO_8601
how to use: toIsoLocalTime(new Date())
function toIsoLocalTime(value) {
if (value instanceof Date === false)
value = new Date();
const off = value.getTimezoneOffset() * -1;
const del = value.getMilliseconds() ? 'Z' : '.'; // have milliseconds ?
value = new Date(value.getTime() + off * 60000); // add or subtract time zone
return value
.toISOString()
.split(del)[0]
+ (off < 0 ? '-' : '+')
+ ('0' + Math.abs(Math.floor(off / 60))).substr(-2)
+ ':'
+ ('0' + Math.abs(off % 60)).substr(-2);
}
function test(value) {
const event = new Date(value);
console.info(value + ' -> ' + toIsoLocalTime(event) + ', test = ' + (event.getTime() === (new Date(toIsoLocalTime(event))).getTime() ));
}
test('2017-06-14T10:00:00+03:00'); // test with timezone
test('2017-06-14T10:00:00'); // test with local timezone
test('2017-06-14T10:00:00Z'); // test with UTC format
test('2099-12-31T23:59:59.999Z'); // date with milliseconds
test((new Date()).toString()); // now
consider using moment (like Matt's answer).
From version 2.20.0, you may call .toISOString(true) to prevent UTC conversion:
console.log(moment().toISOString(true));
// sample output: 2022-04-06T16:26:36.758+03:00
Use Temporal.
Temporal.Now.zonedDateTimeISO().toString()
// '2022-08-09T14:16:47.762797591-07:00[America/Los_Angeles]'
To omit the fractional seconds and IANA time zone:
Temporal.Now.zonedDateTimeISO().toString({
timeZoneName: "never",
fractionalSecondDigits: 0
})
// '2022-08-09T14:18:34-07:00'
Note: Temporal is currently (2022) available as a polyfill, but will soon be available in major browsers.
With luxon:
DateTime.now().toISODate() // 2022-05-23
Here are the functions I used for this end:
function localToGMTStingTime(localTime = null) {
var date = localTime ? new Date(localTime) : new Date();
return new Date(date.getTime() + (date.getTimezoneOffset() * 60000)).toISOString();
};
function GMTToLocalStingTime(GMTTime = null) {
var date = GMTTime ? new Date(GMTTime) : new Date();;
return new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
};
let myDate = new Date(dateToBeFormatted * 1000); // depends if you have milliseconds, or seconds, then the * 1000 might be not, or required.
timeOffset = myDate.getTimezoneOffset();
myDate = new Date(myDate.getTime() - (timeOffset * 60 * 1000));
console.log(myDate.toISOString().split('T')[0]);
Inspired by https://stackoverflow.com/a/29774197/11127383, including timezone offset comment.
a simple way to get:
//using a sample date
let iso_str = '2022-06-11T01:51:59.618Z';
let d = new Date(iso_str);
let tz = 'America/Santiago'
let options = {
timeZone:tz ,
timeZoneName:'longOffset',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
fractionalSecondDigits: 3
}
str_locale = d.toLocaleString("sv-SE",options);
iso_str_tz = str_locale.replace(/(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2}),(\d+)\s+/,'$1-$2-$3T$4:$5:$6.$7').replace('GMT−', '-' ).replace('GMT+','+')
console.log('iso_str : ',iso_str);
console.log('str_locale : ',str_locale);
console.log('iso_str_tz : ',iso_str_tz);
console.log('iso_str_tz --> date : ',new Date(iso_str_tz));
console.log('iso_str_tz --> iso_str: ',new Date(iso_str_tz).toISOString());
Using moment.js, you can use keepOffset parameter of toISOString:
toISOString(keepOffset?: boolean): string;
moment().toISOString(true)
Alternative approach with dayjs
import dayjs from "dayjs"
const formattedDateTime = dayjs(new Date()).format()
console.log(formattedDateTime) // Prints 2022-11-09T07:49:29+03:00
Here's another way a convert your date with an offset.
function toCustomDateString(date, offset) {
function pad(number) {
if (number < 10) {
return "0" + number;
}
return number;
}
var offsetHours = offset / 60;
var offsetMinutes = offset % 60;
var sign = (offset > 0) ? "+" : "-";
offsetHours = pad(Math.floor(Math.abs(offsetHours)));
offsetMinutes = pad(Math.abs(offsetMinutes));
return date.getFullYear() +
"-" + pad(date.getMonth() + 1) +
"-" + pad(date.getDate()) +
"T" + pad(date.getHours()) +
":" + pad(date.getMinutes()) +
":" + pad(date.getSeconds()) +
sign + offsetHours +
":" + offsetMinutes;
}
Then you can use it like this:
var date = new Date();
var offset = 330; // offset in minutes from UTC, for India it is 330 minutes ahead of UTC
var customDateString = toCustomDateString(date, offset);
console.log(customDateString);
// Output: "2023-02-09T10:29:31+05:30"
function setDate(){
var now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
var timeToSet = now.toISOString().slice(0,16);
/*
If you have an element called "eventDate" like the following:
<input type="datetime-local" name="eventdate" id="eventdate" />
and you would like to set the current and minimum time then use the following:
*/
var elem = document.getElementById("eventDate");
elem.value = timeToSet;
elem.min = timeToSet;
}
I found another more easy solution:
let now = new Date();
// correct time zone offset for generating iso string
now.setMinutes(now.getMinutes() - now.getTimezoneOffset())
now = now.toISOString();
I undo the timezone offset by substracting it from the current date object.
The UTC time from the date object is now pointing to the local time.
That gives you the possibility to get the iso date for the local time.

javascript date.toString("yyyy-MM-ddTHH:mm:ss.fffZ") or "yyyy-MM-dd HH:mm:ss ZZ" with timezone offset [duplicate]

Goal: Find the local time and UTC time offset then construct the URL in following format.
Example URL: /Actions/Sleep?duration=2002-10-10T12:00:00−05:00
The format is based on the W3C recommendation. The documentation says:
For example, 2002-10-10T12:00:00−05:00 (noon on 10 October 2002,
Central Daylight Savings Time as well as Eastern Standard Time in the U.S.)
is equal to 2002-10-10T17:00:00Z, five hours later than 2002-10-10T12:00:00Z.
So based on my understanding, I need to find my local time by new Date() then use getTimezoneOffset() function to compute the difference then attach it to the end of string.
Get local time with format
var local = new Date().format("yyyy-MM-ddThh:mm:ss"); // 2013-07-02T09:00:00
Get UTC time offset by hour
var offset = local.getTimezoneOffset() / 60; // 7
Construct URL (time part only)
var duration = local + "-" + offset + ":00"; // 2013-07-02T09:00:00-7:00
The above output means my local time is 2013/07/02 9am and difference from UTC is 7 hours (UTC is 7 hours ahead of local time)
So far it seems to work but what if getTimezoneOffset() returns negative value like -120?
I'm wondering how the format should look like in such case because I cannot figure out from W3C documentation.
Here's a simple helper function that will format JS dates for you.
function toIsoString(date) {
var tzo = -date.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
return (num < 10 ? '0' : '') + num;
};
return date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
dif + pad(Math.floor(Math.abs(tzo) / 60)) +
':' + pad(Math.abs(tzo) % 60);
}
var dt = new Date();
console.log(toIsoString(dt));
getTimezoneOffset() returns the opposite sign of the format required by the spec that you referenced.
This format is also known as ISO8601, or more precisely as RFC3339.
In this format, UTC is represented with a Z while all other formats are represented by an offset from UTC. The meaning is the same as JavaScript's, but the order of subtraction is inverted, so the result carries the opposite sign.
Also, there is no method on the native Date object called format, so your function in #1 will fail unless you are using a library to achieve this. Refer to this documentation.
If you are seeking a library that can work with this format directly, I recommend trying moment.js. In fact, this is the default format, so you can simply do this:
var m = moment(); // get "now" as a moment
var s = m.format(); // the ISO format is the default so no parameters are needed
// sample output: 2013-07-01T17:55:13-07:00
This is a well-tested, cross-browser solution, and has many other useful features.
I think it is worth considering that you can get the requested info with just a single API call to the standard library...
new Date().toLocaleString( 'sv', { timeZoneName: 'short' } );
// produces "2019-10-30 15:33:47 GMT−4"
You would have to do text swapping if you want to add the 'T' delimiter, remove the 'GMT-', or append the ':00' to the end.
But then you can easily play with the other options if you want to eg. use 12h time or omit the seconds etc.
Note that I'm using Sweden as locale because it is one of the countries that uses ISO 8601 format. I think most of the ISO countries use this 'GMT-4' format for the timezone offset other then Canada which uses the time zone abbreviation eg. "EDT" for eastern-daylight-time.
You can get the same thing from the newer standard i18n function "Intl.DateTimeFormat()"
but you have to tell it to include the time via the options or it will just give date.
My answer is a slight variation for those who just want today's date in the local timezone in the YYYY-MM-DD format.
Let me be clear:
My Goal: get today's date in the user's timezone but formatted as ISO8601 (YYYY-MM-DD)
Here is the code:
new Date().toLocaleDateString("sv") // "2020-02-23" //
This works because the Sweden locale uses the ISO 8601 format.
This is my function for the clients timezone, it's lite weight and simple
function getCurrentDateTimeMySql() {
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, 19).replace('T', ' ');
var mySqlDT = localISOTime;
return mySqlDT;
}
Check this:
function dateToLocalISO(date) {
const off = date.getTimezoneOffset()
const absoff = Math.abs(off)
return (new Date(date.getTime() - off*60*1000).toISOString().substr(0,23) +
(off > 0 ? '-' : '+') +
Math.floor(absoff / 60).toFixed(0).padStart(2,'0') + ':' +
(absoff % 60).toString().padStart(2,'0'))
}
// Test it:
d = new Date()
dateToLocalISO(d)
// ==> '2019-06-21T16:07:22.181-03:00'
// Is similar to:
moment = require('moment')
moment(d).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
// ==> '2019-06-21T16:07:22.181-03:00'
You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.
Date.prototype.getISOTimezoneOffset = function () {
const offset = this.getTimezoneOffset();
return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
}
Date.prototype.toISOLocaleString = function () {
return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
this.getMilliseconds().leftPad(3);
}
Number.prototype.leftPad = function (size) {
var s = String(this);
while (s.length < (size || 2)) {
s = "0" + s;
}
return s;
}
Example usage:
var date = new Date();
console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
// Prints "2020-08-05T16:15:46.525+10:00"
I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.
(The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString for anyone without said library.)
Just my two cents here
I was facing this issue with datetimes so what I did is this:
const moment = require('moment-timezone')
const date = moment.tz('America/Bogota').format()
Then save date to db to be able to compare it from some query.
To install moment-timezone
npm i moment-timezone
No moment.js needed: Here's a full round trip answer, from an input type of "datetime-local" which outputs an ISOLocal string to UTCseconds at GMT and back:
<input type="datetime-local" value="2020-02-16T19:30">
isoLocal="2020-02-16T19:30"
utcSeconds=new Date(isoLocal).getTime()/1000
//here you have 1581899400 for utcSeconds
let isoLocal=new Date(utcSeconds*1000-new Date().getTimezoneOffset()*60000).toISOString().substring(0,16)
2020-02-16T19:30
date to ISO string,
with local(computer) time zone,
with or without milliseconds
ISO ref: https://en.wikipedia.org/wiki/ISO_8601
how to use: toIsoLocalTime(new Date())
function toIsoLocalTime(value) {
if (value instanceof Date === false)
value = new Date();
const off = value.getTimezoneOffset() * -1;
const del = value.getMilliseconds() ? 'Z' : '.'; // have milliseconds ?
value = new Date(value.getTime() + off * 60000); // add or subtract time zone
return value
.toISOString()
.split(del)[0]
+ (off < 0 ? '-' : '+')
+ ('0' + Math.abs(Math.floor(off / 60))).substr(-2)
+ ':'
+ ('0' + Math.abs(off % 60)).substr(-2);
}
function test(value) {
const event = new Date(value);
console.info(value + ' -> ' + toIsoLocalTime(event) + ', test = ' + (event.getTime() === (new Date(toIsoLocalTime(event))).getTime() ));
}
test('2017-06-14T10:00:00+03:00'); // test with timezone
test('2017-06-14T10:00:00'); // test with local timezone
test('2017-06-14T10:00:00Z'); // test with UTC format
test('2099-12-31T23:59:59.999Z'); // date with milliseconds
test((new Date()).toString()); // now
consider using moment (like Matt's answer).
From version 2.20.0, you may call .toISOString(true) to prevent UTC conversion:
console.log(moment().toISOString(true));
// sample output: 2022-04-06T16:26:36.758+03:00
Use Temporal.
Temporal.Now.zonedDateTimeISO().toString()
// '2022-08-09T14:16:47.762797591-07:00[America/Los_Angeles]'
To omit the fractional seconds and IANA time zone:
Temporal.Now.zonedDateTimeISO().toString({
timeZoneName: "never",
fractionalSecondDigits: 0
})
// '2022-08-09T14:18:34-07:00'
Note: Temporal is currently (2022) available as a polyfill, but will soon be available in major browsers.
With luxon:
DateTime.now().toISODate() // 2022-05-23
Here are the functions I used for this end:
function localToGMTStingTime(localTime = null) {
var date = localTime ? new Date(localTime) : new Date();
return new Date(date.getTime() + (date.getTimezoneOffset() * 60000)).toISOString();
};
function GMTToLocalStingTime(GMTTime = null) {
var date = GMTTime ? new Date(GMTTime) : new Date();;
return new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
};
let myDate = new Date(dateToBeFormatted * 1000); // depends if you have milliseconds, or seconds, then the * 1000 might be not, or required.
timeOffset = myDate.getTimezoneOffset();
myDate = new Date(myDate.getTime() - (timeOffset * 60 * 1000));
console.log(myDate.toISOString().split('T')[0]);
Inspired by https://stackoverflow.com/a/29774197/11127383, including timezone offset comment.
a simple way to get:
//using a sample date
let iso_str = '2022-06-11T01:51:59.618Z';
let d = new Date(iso_str);
let tz = 'America/Santiago'
let options = {
timeZone:tz ,
timeZoneName:'longOffset',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
fractionalSecondDigits: 3
}
str_locale = d.toLocaleString("sv-SE",options);
iso_str_tz = str_locale.replace(/(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2}),(\d+)\s+/,'$1-$2-$3T$4:$5:$6.$7').replace('GMT−', '-' ).replace('GMT+','+')
console.log('iso_str : ',iso_str);
console.log('str_locale : ',str_locale);
console.log('iso_str_tz : ',iso_str_tz);
console.log('iso_str_tz --> date : ',new Date(iso_str_tz));
console.log('iso_str_tz --> iso_str: ',new Date(iso_str_tz).toISOString());
Using moment.js, you can use keepOffset parameter of toISOString:
toISOString(keepOffset?: boolean): string;
moment().toISOString(true)
Alternative approach with dayjs
import dayjs from "dayjs"
const formattedDateTime = dayjs(new Date()).format()
console.log(formattedDateTime) // Prints 2022-11-09T07:49:29+03:00
Here's another way a convert your date with an offset.
function toCustomDateString(date, offset) {
function pad(number) {
if (number < 10) {
return "0" + number;
}
return number;
}
var offsetHours = offset / 60;
var offsetMinutes = offset % 60;
var sign = (offset > 0) ? "+" : "-";
offsetHours = pad(Math.floor(Math.abs(offsetHours)));
offsetMinutes = pad(Math.abs(offsetMinutes));
return date.getFullYear() +
"-" + pad(date.getMonth() + 1) +
"-" + pad(date.getDate()) +
"T" + pad(date.getHours()) +
":" + pad(date.getMinutes()) +
":" + pad(date.getSeconds()) +
sign + offsetHours +
":" + offsetMinutes;
}
Then you can use it like this:
var date = new Date();
var offset = 330; // offset in minutes from UTC, for India it is 330 minutes ahead of UTC
var customDateString = toCustomDateString(date, offset);
console.log(customDateString);
// Output: "2023-02-09T10:29:31+05:30"
function setDate(){
var now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
var timeToSet = now.toISOString().slice(0,16);
/*
If you have an element called "eventDate" like the following:
<input type="datetime-local" name="eventdate" id="eventdate" />
and you would like to set the current and minimum time then use the following:
*/
var elem = document.getElementById("eventDate");
elem.value = timeToSet;
elem.min = timeToSet;
}
I found another more easy solution:
let now = new Date();
// correct time zone offset for generating iso string
now.setMinutes(now.getMinutes() - now.getTimezoneOffset())
now = now.toISOString();
I undo the timezone offset by substracting it from the current date object.
The UTC time from the date object is now pointing to the local time.
That gives you the possibility to get the iso date for the local time.

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

Goal: Find the local time and UTC time offset then construct the URL in following format.
Example URL: /Actions/Sleep?duration=2002-10-10T12:00:00−05:00
The format is based on the W3C recommendation. The documentation says:
For example, 2002-10-10T12:00:00−05:00 (noon on 10 October 2002,
Central Daylight Savings Time as well as Eastern Standard Time in the U.S.)
is equal to 2002-10-10T17:00:00Z, five hours later than 2002-10-10T12:00:00Z.
So based on my understanding, I need to find my local time by new Date() then use getTimezoneOffset() function to compute the difference then attach it to the end of string.
Get local time with format
var local = new Date().format("yyyy-MM-ddThh:mm:ss"); // 2013-07-02T09:00:00
Get UTC time offset by hour
var offset = local.getTimezoneOffset() / 60; // 7
Construct URL (time part only)
var duration = local + "-" + offset + ":00"; // 2013-07-02T09:00:00-7:00
The above output means my local time is 2013/07/02 9am and difference from UTC is 7 hours (UTC is 7 hours ahead of local time)
So far it seems to work but what if getTimezoneOffset() returns negative value like -120?
I'm wondering how the format should look like in such case because I cannot figure out from W3C documentation.
Here's a simple helper function that will format JS dates for you.
function toIsoString(date) {
var tzo = -date.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
return (num < 10 ? '0' : '') + num;
};
return date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
dif + pad(Math.floor(Math.abs(tzo) / 60)) +
':' + pad(Math.abs(tzo) % 60);
}
var dt = new Date();
console.log(toIsoString(dt));
getTimezoneOffset() returns the opposite sign of the format required by the spec that you referenced.
This format is also known as ISO8601, or more precisely as RFC3339.
In this format, UTC is represented with a Z while all other formats are represented by an offset from UTC. The meaning is the same as JavaScript's, but the order of subtraction is inverted, so the result carries the opposite sign.
Also, there is no method on the native Date object called format, so your function in #1 will fail unless you are using a library to achieve this. Refer to this documentation.
If you are seeking a library that can work with this format directly, I recommend trying moment.js. In fact, this is the default format, so you can simply do this:
var m = moment(); // get "now" as a moment
var s = m.format(); // the ISO format is the default so no parameters are needed
// sample output: 2013-07-01T17:55:13-07:00
This is a well-tested, cross-browser solution, and has many other useful features.
I think it is worth considering that you can get the requested info with just a single API call to the standard library...
new Date().toLocaleString( 'sv', { timeZoneName: 'short' } );
// produces "2019-10-30 15:33:47 GMT−4"
You would have to do text swapping if you want to add the 'T' delimiter, remove the 'GMT-', or append the ':00' to the end.
But then you can easily play with the other options if you want to eg. use 12h time or omit the seconds etc.
Note that I'm using Sweden as locale because it is one of the countries that uses ISO 8601 format. I think most of the ISO countries use this 'GMT-4' format for the timezone offset other then Canada which uses the time zone abbreviation eg. "EDT" for eastern-daylight-time.
You can get the same thing from the newer standard i18n function "Intl.DateTimeFormat()"
but you have to tell it to include the time via the options or it will just give date.
My answer is a slight variation for those who just want today's date in the local timezone in the YYYY-MM-DD format.
Let me be clear:
My Goal: get today's date in the user's timezone but formatted as ISO8601 (YYYY-MM-DD)
Here is the code:
new Date().toLocaleDateString("sv") // "2020-02-23" //
This works because the Sweden locale uses the ISO 8601 format.
This is my function for the clients timezone, it's lite weight and simple
function getCurrentDateTimeMySql() {
var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, 19).replace('T', ' ');
var mySqlDT = localISOTime;
return mySqlDT;
}
Check this:
function dateToLocalISO(date) {
const off = date.getTimezoneOffset()
const absoff = Math.abs(off)
return (new Date(date.getTime() - off*60*1000).toISOString().substr(0,23) +
(off > 0 ? '-' : '+') +
Math.floor(absoff / 60).toFixed(0).padStart(2,'0') + ':' +
(absoff % 60).toString().padStart(2,'0'))
}
// Test it:
d = new Date()
dateToLocalISO(d)
// ==> '2019-06-21T16:07:22.181-03:00'
// Is similar to:
moment = require('moment')
moment(d).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
// ==> '2019-06-21T16:07:22.181-03:00'
You can achieve this with a few simple extension methods. The following Date extension method returns just the timezone component in ISO format, then you can define another for the date/time part and combine them for a complete date-time-offset string.
Date.prototype.getISOTimezoneOffset = function () {
const offset = this.getTimezoneOffset();
return (offset < 0 ? "+" : "-") + Math.floor(Math.abs(offset / 60)).leftPad(2) + ":" + (Math.abs(offset % 60)).leftPad(2);
}
Date.prototype.toISOLocaleString = function () {
return this.getFullYear() + "-" + (this.getMonth() + 1).leftPad(2) + "-" +
this.getDate().leftPad(2) + "T" + this.getHours().leftPad(2) + ":" +
this.getMinutes().leftPad(2) + ":" + this.getSeconds().leftPad(2) + "." +
this.getMilliseconds().leftPad(3);
}
Number.prototype.leftPad = function (size) {
var s = String(this);
while (s.length < (size || 2)) {
s = "0" + s;
}
return s;
}
Example usage:
var date = new Date();
console.log(date.toISOLocaleString() + date.getISOTimezoneOffset());
// Prints "2020-08-05T16:15:46.525+10:00"
I know it's 2020 and most people are probably using Moment.js by now, but a simple copy & pastable solution is still sometimes handy to have.
(The reason I split the date/time and offset methods is because I'm using an old Datejs library which already provides a flexible toString method with custom format specifiers, but just doesn't include the timezone offset. Hence, I added toISOLocaleString for anyone without said library.)
Just my two cents here
I was facing this issue with datetimes so what I did is this:
const moment = require('moment-timezone')
const date = moment.tz('America/Bogota').format()
Then save date to db to be able to compare it from some query.
To install moment-timezone
npm i moment-timezone
No moment.js needed: Here's a full round trip answer, from an input type of "datetime-local" which outputs an ISOLocal string to UTCseconds at GMT and back:
<input type="datetime-local" value="2020-02-16T19:30">
isoLocal="2020-02-16T19:30"
utcSeconds=new Date(isoLocal).getTime()/1000
//here you have 1581899400 for utcSeconds
let isoLocal=new Date(utcSeconds*1000-new Date().getTimezoneOffset()*60000).toISOString().substring(0,16)
2020-02-16T19:30
date to ISO string,
with local(computer) time zone,
with or without milliseconds
ISO ref: https://en.wikipedia.org/wiki/ISO_8601
how to use: toIsoLocalTime(new Date())
function toIsoLocalTime(value) {
if (value instanceof Date === false)
value = new Date();
const off = value.getTimezoneOffset() * -1;
const del = value.getMilliseconds() ? 'Z' : '.'; // have milliseconds ?
value = new Date(value.getTime() + off * 60000); // add or subtract time zone
return value
.toISOString()
.split(del)[0]
+ (off < 0 ? '-' : '+')
+ ('0' + Math.abs(Math.floor(off / 60))).substr(-2)
+ ':'
+ ('0' + Math.abs(off % 60)).substr(-2);
}
function test(value) {
const event = new Date(value);
console.info(value + ' -> ' + toIsoLocalTime(event) + ', test = ' + (event.getTime() === (new Date(toIsoLocalTime(event))).getTime() ));
}
test('2017-06-14T10:00:00+03:00'); // test with timezone
test('2017-06-14T10:00:00'); // test with local timezone
test('2017-06-14T10:00:00Z'); // test with UTC format
test('2099-12-31T23:59:59.999Z'); // date with milliseconds
test((new Date()).toString()); // now
consider using moment (like Matt's answer).
From version 2.20.0, you may call .toISOString(true) to prevent UTC conversion:
console.log(moment().toISOString(true));
// sample output: 2022-04-06T16:26:36.758+03:00
Use Temporal.
Temporal.Now.zonedDateTimeISO().toString()
// '2022-08-09T14:16:47.762797591-07:00[America/Los_Angeles]'
To omit the fractional seconds and IANA time zone:
Temporal.Now.zonedDateTimeISO().toString({
timeZoneName: "never",
fractionalSecondDigits: 0
})
// '2022-08-09T14:18:34-07:00'
Note: Temporal is currently (2022) available as a polyfill, but will soon be available in major browsers.
With luxon:
DateTime.now().toISODate() // 2022-05-23
Here are the functions I used for this end:
function localToGMTStingTime(localTime = null) {
var date = localTime ? new Date(localTime) : new Date();
return new Date(date.getTime() + (date.getTimezoneOffset() * 60000)).toISOString();
};
function GMTToLocalStingTime(GMTTime = null) {
var date = GMTTime ? new Date(GMTTime) : new Date();;
return new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
};
let myDate = new Date(dateToBeFormatted * 1000); // depends if you have milliseconds, or seconds, then the * 1000 might be not, or required.
timeOffset = myDate.getTimezoneOffset();
myDate = new Date(myDate.getTime() - (timeOffset * 60 * 1000));
console.log(myDate.toISOString().split('T')[0]);
Inspired by https://stackoverflow.com/a/29774197/11127383, including timezone offset comment.
a simple way to get:
//using a sample date
let iso_str = '2022-06-11T01:51:59.618Z';
let d = new Date(iso_str);
let tz = 'America/Santiago'
let options = {
timeZone:tz ,
timeZoneName:'longOffset',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
fractionalSecondDigits: 3
}
str_locale = d.toLocaleString("sv-SE",options);
iso_str_tz = str_locale.replace(/(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2}),(\d+)\s+/,'$1-$2-$3T$4:$5:$6.$7').replace('GMT−', '-' ).replace('GMT+','+')
console.log('iso_str : ',iso_str);
console.log('str_locale : ',str_locale);
console.log('iso_str_tz : ',iso_str_tz);
console.log('iso_str_tz --> date : ',new Date(iso_str_tz));
console.log('iso_str_tz --> iso_str: ',new Date(iso_str_tz).toISOString());
Using moment.js, you can use keepOffset parameter of toISOString:
toISOString(keepOffset?: boolean): string;
moment().toISOString(true)
Alternative approach with dayjs
import dayjs from "dayjs"
const formattedDateTime = dayjs(new Date()).format()
console.log(formattedDateTime) // Prints 2022-11-09T07:49:29+03:00
Here's another way a convert your date with an offset.
function toCustomDateString(date, offset) {
function pad(number) {
if (number < 10) {
return "0" + number;
}
return number;
}
var offsetHours = offset / 60;
var offsetMinutes = offset % 60;
var sign = (offset > 0) ? "+" : "-";
offsetHours = pad(Math.floor(Math.abs(offsetHours)));
offsetMinutes = pad(Math.abs(offsetMinutes));
return date.getFullYear() +
"-" + pad(date.getMonth() + 1) +
"-" + pad(date.getDate()) +
"T" + pad(date.getHours()) +
":" + pad(date.getMinutes()) +
":" + pad(date.getSeconds()) +
sign + offsetHours +
":" + offsetMinutes;
}
Then you can use it like this:
var date = new Date();
var offset = 330; // offset in minutes from UTC, for India it is 330 minutes ahead of UTC
var customDateString = toCustomDateString(date, offset);
console.log(customDateString);
// Output: "2023-02-09T10:29:31+05:30"
function setDate(){
var now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
var timeToSet = now.toISOString().slice(0,16);
/*
If you have an element called "eventDate" like the following:
<input type="datetime-local" name="eventdate" id="eventdate" />
and you would like to set the current and minimum time then use the following:
*/
var elem = document.getElementById("eventDate");
elem.value = timeToSet;
elem.min = timeToSet;
}
I found another more easy solution:
let now = new Date();
// correct time zone offset for generating iso string
now.setMinutes(now.getMinutes() - now.getTimezoneOffset())
now = now.toISOString();
I undo the timezone offset by substracting it from the current date object.
The UTC time from the date object is now pointing to the local time.
That gives you the possibility to get the iso date for the local time.

Categories

Resources