I am using Google Apps Script to check and re-format date data from some Google Sheets. But the problem is the result shows the times for the user who run the code. I want to show the date for any specific time zone. How is it possible?
Suppose, my input is checkDate('14/5/2022'); and it returns the date
object for that time zone instead of my time zone.
Here is my code:
/**
* This will return a JS Date object with a valid date input.
* Unless this will return a false status
*/
function checkDate(input) {
// const timeZone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
if (input instanceof Date && !isNaN(input)) {
// will execute if a valid date
return input;
} else {
// If not a valid date
const splitter = input.indexOf('/') === -1 ? '-' : '/';
const dateArr = input.split(splitter);
if(dateArr.length === 3) {
const year = dateArr[2].length === 2 ? '20' + dateArr[2] : dateArr[2];
const NewTime = new Date(Date.UTC(year, dateArr[1]-1, dateArr[0], 0, 0, 0));
return NewTime;
} else {
return false;
}
}
}
console.log(checkDate(new Date()));
console.log(checkDate('14/5/2022'));
Expected input
checkDate('14/5/2022') and timeZone = 'GMT+1;
Expected Output
2022-05-14T00:00:00.000 french time. Not the UTC time.
Is it possible?
Apps Script is JavaScript, and JavaScript Date objects are always in UTC.
When you return a Date object from a custom function, or directly write a Date object to a spreadsheet cell from another type of function, it is automatically converted to the timezone of the spreadsheet. To set the spreadsheet timezone, choose File > Settings > Time zone.
To write a date so that it appears to use another timezone, convert the Date to a text string for display with Utilities.formatDate(), like this:
const date = new Date();
const timezone = {
spreadsheet: SpreadsheetApp.getActive().getSpreadsheetTimeZone(),
paris: 'Europe/Paris',
};
console.log(Utilities.formatDate(date, timezone.spreadsheet, 'yyyy-MM-dd HH:mm, zzzz'));
console.log(Utilities.formatDate(date, timezone.paris, 'yyyy-MM-dd HH:mm, zzzz'));
2022-05-14T00:00:00.000 is string, so add this function
function myFormat(date) {
return date.getFullYear()
+ '-'
+ ((date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1))
+ '-'
+ (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
+ 'T00:00:00.000'
}
complete script
function checkDate(input) {
// const timeZone = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
if (input instanceof Date && !isNaN(input)) {
// will execute if a valid date
return myFormat(input);
} else {
// If not a valid date
const splitter = input.indexOf('/') === -1 ? '-' : '/';
const dateArr = input.split(splitter);
if (dateArr.length === 3) {
const year = dateArr[2].length === 2 ? '20' + dateArr[2] : dateArr[2];
const NewTime = new Date(Date.UTC(year, dateArr[1] - 1, dateArr[0], 0, 0, 0));
return myFormat(NewTime);
} else {
return false;
}
}
}
function myFormat(date) {
return date.getFullYear()
+ '-'
+ ((date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1))
+ '-'
+ (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
+ 'T00:00:00.000'
}
function test() {
console.log(checkDate('14/05/2022'))
}
I need to take away the day from the date that I get, that is 24 hours minus 23:47:16 I have to get 12:44. I tried to break the date variable into a string and take it away, but I just can’t find the algorithm, maybe this can be done with the moment, tell me please
24:00:00 (minus) (const date or const formattedTime) = ...
(in my example 24:00:00 - 23:47:16 = 12:44)
const date1: any = new Date(Date.now());
const date2: any = new Date(marked_deletion_at);
const diffTime = Math.abs(date2 - date1);
const date = new Date(diffTime);
console.log(date) // Thu Jan 01 1970 23:47:16 GMT+0300
const hours = date.getHours();
const minutes = '0' + date.getMinutes();
const seconds = '0' + date.getSeconds();
// Will display time in 10:30:23 format
const formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime) // 23:47:16
You could do with moment .diff method
const datetime = '2020-02-20 23:47:16';
const your_time = moment(datetime);
const close_time = moment(datetime).endOf('day')
let h = close_time.diff(your_time,'hours')
let m = close_time.diff(your_time,'minutes')
console.log(h+':'+m)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
If you simply want to subtract a time in h:mm:ss format from 24:00:00, then convert to some common base (e.g. seconds), subtract, then convert back to h:mm:ss, e.g.
// Convert time in h:mm:ss format to seconds
function toSecs(time) {
let b = time.split(':');
return b[0]*3600 + b[1]*60 + b[2]*1;
}
// Convert seconds to h:mm:ss format
function toTime(secs) {
return (secs/3600 | 0) + ':' +
('' + ((secs%3600)/60 |0)).padStart(2, '0') + ':' +
('' + (secs%60)).padStart(2, '0');
}
// Time to midnight tonight
let z = n => (n<10?'0':'') + n;
let now = new Date();
let time = now.getHours() + ':' +
z(now.getMinutes()) + ':' +
z(now.getSeconds());
console.log('Current time: ' + time);
console.log('To midnight : ' + toTime(8.64e4 - toSecs(time)))
Note that the functions don't handle negative numbers.
Try this:
var date1 = moment("2020-03-19 23:47:16");
var date2 = moment("2020-03-19 24:00:00");
var hours = date2.diff(date1, "hours");
var mins = moment
.utc(moment(date2, "HH:mm:ss").diff(moment(date1, "HH:mm:ss")))
.format("mm");
var seconds = moment
.utc(moment(date2, "HH:mm:ss").diff(moment(date1, "HH:mm:ss")))
.format("ss");
console.log(hours);
console.log(mins);
console.log(seconds);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
We have created a function in node-red, where we cleaning a datetime received from the metadata of a sensor. Unfortunately, the timezone fetched is one hour behind, and therefore a "wrong datetime" is sent. We need to convert this datetime to UTC+1 ('Europe/Berlin'). The function is in JavaScript, and in my knowledge we can't use third party libraries like moment etc.
Hopefully, someone here can help us. Thanks in advance!
This is what we have done so far:
var time = msg.metadata.time;
var datetime = new Date().toLocaleString();
var timedate = new Date(time);
var y = timedate.getFullYear().toString();
var m = (timedate.getMonth() + 1).toString();
var d = timedate.getDate().toString();
(d.length == 1) && (d = '0' + d);
(m.length == 1) && (m = '0' + m);
timedate.setHours(timedate.getHours() + 1)
var h = timedate.getHours().toString();
var min = timedate.getMinutes().toString();
var s = timedate.getSeconds().toString();
(h.length == 1) && (h = '0' + h);
(min.length == 1) && (min = '0' + min);
(s.length == 1) && (s = '0' + s);
var date = y+'-'+m+'-'+d
var time = h + ":" + min + ":" + s;
var timeDate = date+' '+time;
I would consider using Date.toLocaleString() for date/time conversion.
Now Moment.js will be better if you can use it, but you can convert times like below.
Remember you must consider DST changes and these are hard to account for using your own code (the exact dates of DST switchover change from year to year).
For example, Berlin uses CET (UTC+1) from late October to late March and CEST (UTC+2) from late March to late October.
Why am I using a locale of "sv", this is because it will essentially give us an ISO 8601 timestamp. Of course for converting to text you can use any locale.
I've added a getUTCOffsetMinutes function that will return the UTC offset in minutes for a given UTC time and timezone.
A list of IANA timezones is here: timezone list
const time = 1559347200000; // 2019-06-01T00:00:00Z
console.log("UTC time 1:", new Date(time).toISOString());
console.log("Berlin time 1 (ISO):", new Date(time).toLocaleString("sv", { timeZone: "Europe/Berlin"}));
console.log("Berlin time 1 (de):", new Date(time).toLocaleString("de", { timeZone: "Europe/Berlin"}));
const time2 = 1575158400000; // 2019-12-01T00:00:00Z
console.log("UTC time 2:", new Date(time2).toISOString());
console.log("Berlin time 2 (ISO):", new Date(time2).toLocaleString("sv", { timeZone: "Europe/Berlin"}));
console.log("Berlin time 2 (de):", new Date(time2).toLocaleString("de", { timeZone: "Europe/Berlin"}));
// You can also get the UTC offset using a simple enough function:
// Again, this will take into account DST
function getUTCOffsetMinutes(unixDate, tz) {
const localTimeISO = new Date(unixDate).toLocaleString("sv", {timeZone: tz}).replace(" ", "T") + "Z";
return (new Date(localTimeISO).getTime() - unixDate) / 60000; // Milliseconds to minutes.
}
console.log("UTC offset minutes (June/Berlin):", getUTCOffsetMinutes(time, "Europe/Berlin"));
console.log("UTC offset minutes (June/LA):", getUTCOffsetMinutes(time, "America/Los_Angeles"));
console.log("UTC offset minutes (June/Sydney):",getUTCOffsetMinutes(time, "Australia/Sydney"));
console.log("UTC offset minutes (December/Berlin):", getUTCOffsetMinutes(time2, "Europe/Berlin"));
console.log("UTC offset minutes (December/LA):", getUTCOffsetMinutes(time2, "America/Los_Angeles"));
console.log("UTC offset minutes (December/Sydney):", getUTCOffsetMinutes(time2, "Australia/Sydney"));
I use this function I made, i think it may help you:
function formatDateToOffset(date, timeOffset){
var dateInfo, timeInfo;
// change date's hours based on offset
date.setHours(date.getHours() + (timeOffset || 0))
// place it the way you want to format
dateInfo = [date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()]
timeInfo = [date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()];
// return the string formatted date
return dateInfo.join("-") + " " + timeInfo.join(":");
}
console.log(formatDateToOffset(new Date(), 1))
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.
I am using a form ,from which the user can select the datetime from datetime picker in dd-mm-yyyy hh:mm:ss format. Now I want to convert the format to yyyy-mm-dd hh:mm:ss format to store in mysql table.
I tried with moment js like this
console.log(moment(status.date).format('MM/DD/YYYY'));
where status.date I will post from a form where the user selects datetime from datetimepicker.
Please help
You can do like this instead of having some modules.
var fd = status.date;
var fromDate = fd.split(" ");
console.log(formatDate(fromDate[0],fromDate[1] + " " + fromDate[2]));//
and add these functions there.
function formatDate(date, time2) {
var from = date.split("-");
var f = from[2] + "-" + from[1] + "-" + from[0];
var time1 = time(time2);
return f + " " + time1;
}
function time(time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if ((AMPM == "PM" || AMPM == "pm") && hours < 12)
hours = hours + 12;
if ((AMPM == "AM" || AMPM == "am") && hours == 12)
hours = hours - 12;
var sHours = hours.toString();
if (hours < 10)
sHours = "0" + sHours;
if (minutes < 10)
sMinutes = "0" + sMinutes;
return (sHours + ":" + sMinutes);
}
Convert it to ISOString first and then eliminate unwanted things by replace method.
var date = new Date();
date.toISOString().replace(/T/, " ").replace(/\..+/,'')
source: chbrown's answer
Building on top of Prateek Jain's ISOString method, we can use toLocaleString to obtain the local time in ISO format.
One needs to shop around the base format provided by toLocaleString according to different regions. The format closest to ISO is en-CA (refer to this answer for all the region-based format). We then use the option {hour12: false} to convert to 24-hour notation.
const d = new Date();
d.toLocaleString('en-CA', {hour12: false}).replace(/, /, ' ');