Convert Epoch time to human readable with specific timezone - javascript

To convert epoch dateTime to human readable , using a simple new date(1495159447834) will suffice.
The problem I'm encountering now is that for my hybrid application, if the user set the time-zone in his phone date time setting to lets say GMT +12:00 ,the human readable dateTime will be different from what I would want the user to have and I would want him/her to follow the server timezone.
Thus , how would I convert the epoch number to a specific given timezone in a human readable format.
I have tried example like:
var test= new Date('1495159447834 GMT+0800').toString();
and it returns me an Invalid Date.
If possible, I would want this without any libraries. I have looked through the answers here and I believe that I could not find any answers I'm looking for. If there is any previously answered question with the same topic, do let me know and I will close this question!

You can use offset to convert your current datetime to a specific timezone.
function convertEpochToSpecificTimezone(timeEpoch, offset){
var d = new Date(timeEpoch);
var utc = d.getTime() + (d.getTimezoneOffset() * 60000); //This converts to UTC 00:00
var nd = new Date(utc + (3600000*offset));
return nd.toLocaleString();
}
// convertEpochToSpecificTimezone(1495159447834, +3)
The offset will be your specific timezone. Example: GMT +03:00, your offset is +3. If GMT -10:00, offset is -10

there are number of ways to convert between Epoch and Human readable format
//Convert epoch to human readable date
var myDate = new Date( 1533132667*1000);
document.write(myDate.toGMTString()+"<hr>"+myDate.toLocaleString());
//this will return Wed, 01 Aug 2018 14:11:07 GMT
//Convert human readable dates to epoch
var myDate = new Date("Wed Aug 01 2018 14:11:07 GMT");
var myEpoch = myDate.getTime()/1000.0;
// this will return 1533132667
For Reference: https://www.epochconverter.com/programming/#javascript
Edit#
added a JSFiddle here

This is old, but I did it this way:
function formatDate(date, includeTime) {
const dateTimeFormat = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
timeZone: 'America/Los_Angeles',
timeZoneName: 'short',
});
const [
{ value: month },
,
{ value: day },
,
{ value: year },
,
{ value: hour },
,
{ value: minute },
,
{ value: dayPeriod },
,
{ value: timeZoneName },
] = dateTimeFormat.formatToParts(date);
if (includeTime) {
return `${day} ${month} ${year} • ${hour}:${minute}${dayPeriod.toLowerCase()} ${timeZoneName}`;
}
return `${day} ${month} ${year}`;
This will output the time of the given timezone.
For example, if I have an epoch time (unix timestamp) and if I'm in Argentina, the time should be displayed as 03:45 GMT -3 of June 2, but with this code, it will be displayed as the time that should be displayed for Los Angeles.
My requirement was to display time in Los Angeles timezone, even if I visit the page from Argentina.

set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to
the epoch
d.setUTCSeconds(utcSeconds);
Or you can use momentjs
moment.unix(yourUnixEpochTime).format('dddd, MMMM Do, YYYY h:mm:ss A')
or you can use this way
var dateVal ="/Date(1342709595000)/";
var date = new Date(parseFloat(dateVal.substr(6)));
document.write(
(date.getMonth() + 1) + "/" +
date.getDate() + "/" +
date.getFullYear() + " " +
date.getHours() + ":" +
date.getMinutes() + ":" +
date.getSeconds()
);

Related

How can I get the epoch time for a specific time of day in a specific timezone?

I'm trying to get the epoch timestamp, for the current day, in a specific timezone.
eg I want to know the epoch timestamp for 6am today in Pacific Standard time
I'm pretty close, but not sure how to adjust for the timezone:
const getTimestampFor10amPST = () => {
const today = new Date()
const year = today.getFullYear()
const month = today.getMonth()
const day = today.getDate()
const timestampFor10amPST = new Date(year, month, day, 10, 0, 0, 0);
return timestampFor10amPST.getTime()
}
How can I get this timestamp for the expected timezone?
You can do this using Luxon:
const dt = luxon.DateTime.fromObject({hour: 10, zone: 'America/Los_Angeles'});
console.log('Time in time zone: ' + dt.toString());
console.log('Unix (epoch) timestamp in milliseconds: ' + dt.toMillis());
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.25.0/luxon.min.js"></script>
This works because when you don't provide date components, Luxon uses the current date in the provided time zone as a basis. Also, when you provide any time components, the remaining time components are set to zero. Thus all you need to set are the hour and time zone.
Try something like this:
function calcTime(city, offset) {
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));
return "The local time in " + city + " is " + nd.toLocaleString();
}
// get Bombay time
console.log(calcTime('Bombay', '+5.5'));
// get Singapore time
console.log(calcTime('Singapore', '+8'));
// get London time
console.log(calcTime('London', '+1'));
another way to do it is using the options object as it has a timeZoneName parameter
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// an application may want to use UTC and make that visible
var options = { timeZone: 'UTC', timeZoneName: 'short' };
console.log(date.toLocaleTimeString('en-US', options));
// → "3:00:00 AM GMT"
// sometimes even the US needs 24-hour time
console.log(date.toLocaleTimeString('en-US', { hour12: false }));
// → "19:00:00"
// show only hours and minutes, use options with the default locale - use an empty array
console.log(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }));
// → "20:01"
If you want it to return a date object instead of a string, the following solution will work for you:
var d = new Date();
var date_object = new Date(formatDate(d.toLocaleString('en-US', { 'timeZone': 'America/New_York', 'hour12': false })));
function formatDate(date){
var date = date.split(', ')[0].split('/');
var time = date.split(', ')[1].split(':');
return date[2]+'-'+date[0]+'-'+date[1]+'T'+time[0]+':'+time[1]+':'+time[2];
}

How to convert a non local javascript date timezone to UTC?

How can I convert a date to UTC from a specific timezone?
In javascript you can convert a local date to utc and create a date from a date string or utc string.
The intl built in functions allow you to convert a datetime to a timezone, but not back to utc. I could not find any specific questions on this amazingly all others say local time.
I know that in moment you can convert a UTC from a timezone, like this:
var now = moment();
console.log(now.format('YYYY-MM-DD HH:mm:ss'))
console.log(now.utc().format('YYYY-MM-DD HH:mm:ss'))
console.log(now.tz("Australia/Sydney").format('YYYY-MM-DD HH:mm:ss'))
console.log(now.tz("Australia/Sydney").utc().format('YYYY-MM-DD HH:mm:ss'))
console.log(now.tz("Australia/Sydney").tz("Asia/Tokyo").format('YYYY-MM-DD HH:mm:ss'))
console.log(now.tz("Australia/Sydney").tz("Asia/Tokyo").utc().format('YYYY-MM-DD HH:mm:ss'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.25/moment-timezone-with-data.min.js"></script>
The utcs should match. Aside from using moment, what other ways (browser, node, libraries) are there to convert a date considering it's in a timezone that is not local in the browser using js to utc? Doesn’t need to be vanilla js.
Here was my javascript native vanillajs solution using Intl.DateTimeFormat()
Basically I get the difference in the timezone specified and the local time. I add that difference then set return the utc.
/**
* take a date of assumed timezone and convert to utc
*
* #param {*} d
* #param {*} tz
* #returns
*/
function tzUTC(d, tz) {
// first calculate tz difference
// use passed in date to get timezone difference as close to that day.
var date = new Date(d);
var options = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
timeZone: tz
};
var tzDate = new Intl.DateTimeFormat('en-US', options).format(date)
var diff = date - new Date(tzDate);
var minutes = Math.floor((diff / 1000) / 60);
var localTime = new Date(d);
localTime.setMinutes(d.getMinutes() + minutes);
return localTime.toUTCString();
}
var d = new Date("5/18/2019, 07:49:13");
// Fri May 17 2019 17:49:13 GMT-0400 (Eastern Daylight Time)
// utc should be Fri, 17 May 2019 21:49:13 GMT"
//
console.log("d:" + d)
console.log("tzUTC:" + tzUTC(d, 'Australia/Sydney'))
d = new Date("5/17/2019, 14:53:21");
console.log("d:" + d)
// Fri May 17 2019 17:53:21 GMT-0400 (Eastern Daylight Time)
// utc "Fri, 17 May 2019 21:53:21 GMT"
console.log("tzUTC:" + tzUTC(d, 'America/Los_Angeles'))

how to get this specific datetime format in javascript

In javascript, is there a way to convert a date time to the following format:
// 11/3/18, 12:00 AM
Date().toString() gives me:
Sat Nov 03 2018 00:00:00 GMT+0000 (UTC)
Thanks.
This is an alternative to format dates, the function Date.prototype.toLocaleDateString allows you to format date according to options/flags.
Some js engines manage the format process differently (so, this is implementation dependent), therefore be careful. Further, you need to check for compatibility in browsers.
let today = new Date();
var options = { year: 'numeric', month: 'numeric', day: 'numeric', hour12: true, hour: 'numeric', minute: 'numeric' };
console.log(today.toLocaleDateString('en-US', options));
tl;dr: try typing this in your browser's javascript console on the moment.js website: moment().format('MM/d/YY h:mm A')
Three things:
1. If you haven't already, check out these date docs for the API:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
(Thorough backgrounder): https://www.toptal.com/software/definitive-guide-to-datetime-manipulation
2. Without an external library
See Ele's answer above for most elegant non-library: https://stackoverflow.com/a/53135859/3191929
Ex. Extract mm/dd/yy from Date
const root = new Date();
let month = root.getMonth(); // 0 to 11
let day = root.getDate(); // 1 to 31
let year = root.getFullYear(); year = String(year).slice(2);
// 11/3/18, 12:00 AM mm/dd/yy, hh:mm AM/PM
const output = ``${month}/${day}/${year}``; // mm/dd/yy
And from there you can explore the API to get the 24 hours, then do a check for AM/PM and build the result etc etc. (see bbram's answer here: https://stackoverflow.com/a/8888498/3191929 for the relevant Date APIs for time)
Here's a quick'n'dirty solution to your specific question
Ex. Extract mm/dd/yy hh:mm AM/PM from Date
function formatDate(root) {
let month = root.getMonth(); // 0 to 11, 0 = Jan
month += 1; // 1 to 12, 1 = Jan
let day = root.getDate(); // 1 to 31
let year = root.getFullYear();
year = String(year).slice(2);
// Time transformation appropriated from bbrame
// https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format/8888498#8888498
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
// mm/dd/yy, hh:mm AM/PM
const output = `${month}/${day}/${year} ${formatAMPM(root)}`;
return output;
}
var rootDate = new Date();
console.log(formatDate(rootDate)); // mm/dd/yy hh:mm AM/PM
3. With an external library
Using moment.js you can achieve the above with just this:
var root = moment(); // valid moment date
var formatted = root.format('m/d/YY h:mm A');
See the moment.js docs for more details: https://momentjs.com/docs/#/displaying/format/
If momentjs specifically is a no-go, see here for other options as well: https://github.com/you-dont-need/You-Dont-Need-Momentjs

How can I convert string formatted UTC dates without offset to local time in JavaScript?

I am getting a string formatted date with UTC timezone. I need to convert this date time in user's current time zone using jquery or javascript.
I am getting this:
9:43pm 16/10/2015 //this is UTC time, I am getting this via an ajax call
I need to convert it to this:
12:00pm 16/10/2015 //whatever time by that location
If you can pick that format apart, or get a standard format JavaScript can parse - you can convert it to a Date object. I'm not seeing an offset on that date which is problematic when JavaScript tries to parse it. Assuming that is all you have, we can force a UTC date with the following...
// ------- new Date(Date.UTC(year, month, day, hour, minute, second))
var date = new Date(Date.UTC(2015, 9, 16, 21, 43, 0));
console.log(date) // Fri Oct 16 2015 15:43:00 GMT-0600 (Mountain Daylight Time (Mexico))
note that month in Date.UTC is zero based e.g. October would be 9
new Date(value) would do this for us automatically if the format is correct - where value is the actual date value you receive - but that format will not parse as is. If there is no way around that format, you can manipulate it to work in the above example. Here is an untested algorithm for your example...
var formatted = '9:43pm 16/10/2015'
function createDateUTC(formatted) {
var hourOffset = formatted.split(' ')[0].split(':')[1].match(/[a-zA-Z]+/g)[0] === 'pm' ? 12 : 0
var year = parseInt(formatted.split('/').pop());
var month = parseInt(formatted.split('/')[1]) - 1;
var day = parseInt(formatted.split('/')[0].split(' ').pop());
var hour = hourOffset + parseInt(formatted.split(' ')[0].split(':')[0]);
var minute = parseInt(formatted.split(' ')[0].split(':')[1]);
return new Date(Date.UTC(year, month, day, hour, minute, 0));
}
var myDate = createDateUTC(formatted);
JSFiddle Link - working demo
Check out the UTC() and Date Object docs for more info
Additionally, to get the exact format you want, we can introduce some more functions which will give us the 12:00pm 16/10/2015 format
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + '' + ampm;
return strTime;
}
function formatMMDDYYYY(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
console.log(formatAMPM(myDate) + ' ' + formatMMDDYYYY(myDate));
// Mountain Daylight Time => -- 3:43pm 16/10/2015
JSFiddle Link - formatted example
I'd reccoment looking into Moment.js if you plan to do heavy date formatting and manipulation.
Overall - the best solution to this would be to return an acceptable format from the server, resolve it to local time natively e.g. new Date(), and use a robust formatting library as opposed to rolling your own to display it how you wish.
You should process that string a little bit to extract year, month, day, hour and minute.
Then you can create a local date with that UTC date using this:
var time = new Date ( Date.UTC('year', 'month', 'day', 'hour', 'minute') );
In my case, '9:43pm 16/10/2015' returns: 'Mon Nov 16 2015 07:43:00 GMT-0200 (Hora de verano de Argentina)'.

How to convert an ISO date to the date format yyyy-mm-dd?

How can I get a date having the format yyyy-mm-dd from an ISO 8601 date?
My 8601 date is
2013-03-10T02:00:00Z
How can I get the following?
2013-03-10
Just crop the string:
var date = new Date("2013-03-10T02:00:00Z");
date.toISOString().substring(0, 10);
Or if you need only date out of string.
var strDate = "2013-03-10T02:00:00Z";
strDate.substring(0, 10);
Try this
date = new Date('2013-03-10T02:00:00Z');
date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();//prints expected format.
Update:-
As pointed out in comments, I am updating the answer to print leading zeros for date and month if needed.
date = new Date('2013-08-03T02:00:00Z');
year = date.getFullYear();
month = date.getMonth()+1;
dt = date.getDate();
if (dt < 10) {
dt = '0' + dt;
}
if (month < 10) {
month = '0' + month;
}
console.log(year+'-' + month + '-'+dt);
You could checkout Moment.js, Luxon, date-fns or Day.js for nice date manipulation.
Or just extract the first part of your ISO string, it already contains what you want.
Here is an example by splitting on the T:
"2013-03-10T02:00:00Z".split("T")[0] // "2013-03-10"
And another example by extracting the 10 first characters:
"2013-03-10T02:00:00Z".substr(0, 10) // "2013-03-10"
This is what I do to get date only:
let isoDate = "2013-03-10T02:00:00Z";
alert(isoDate.split("T")[0]);
let isoDate = "2013-03-10T02:00:00Z";
var d = new Date(isoDate);
d.toLocaleDateString('en-GB'); // dd/mm/yyyy
d.toLocaleDateString('en-US'); // mm/dd/yyyy
Moment.js will handle date formatting for you. Here is how to include it via a JavaScript tag, and then an example of how to use Moment.js to format a date.
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
moment("2013-03-10T02:00:00Z").format("YYYY-MM-DD") // "2013-03-10"
Moment.js is pretty big library to use for a single use case. I recommend using date-fns instead. It offers basically the most functionality of Moment.js with a much smaller bundle size and many formatting options.
import format from 'date-fns/format'
format('2013-03-10T02:00:00Z', 'YYYY-MM-DD'); // 2013-03-10, YYYY-MM-dd for 2.x
One thing to note is that, since it's the ISO 8601 time format, the browser generally converts from UTC time to local timezone. Though this is simple use case where you can probably do '2013-03-10T02:00:00Z'.substring(0, 10);.
For more complex conversions date-fns is the way to go.
UPDATE: This no longer works with Firefox and Chromium v110+ (Feb 2023) because the 'en-CA' locale now returns the US date format.
Using toLocaleDateString with the Canadian locale returns a date in ISO format.
function getISODate(date) {
return date.toLocaleDateString('en-ca');
}
getISODate(new Date()); // '2022-03-24'
To all who are using split, slice and other string-based attempts to obtain the date, you might set yourself up for timezone related fails!
An ISO-String has Zulu-Timezone and a date according to this timezone, which means, it might use a date a day prior or later to the actual timezone, which you have to take into account in your transformation chain.
See this example:
const timeZoneRelatedDate = new Date(2020, 0, 14, 0, 0);
console.log(timeZoneRelatedDate.toLocaleDateString(
'ja-JP',
{
year: 'numeric',
month: '2-digit',
day: '2-digit'
}
).replace(/\//gi,'-'));
// RESULT: "2020-01-14"
console.log(timeZoneRelatedDate.toISOString());
// RESULT: "2020-01-13T23:00:00.000Z" (for me in UTC+1)
console.log(timeZoneRelatedDate.toISOString().slice(0,10));
// RESULT: "2020-01-13"
Use:
new Date().toISOString().substring(0, 10);
This will output the date in YYYY-MM-DD format:
let date = new Date();
date = date.toISOString().slice(0,10);
The best way to format is by using toLocaleDateString with options
const options = {year: 'numeric', month: 'numeric', day: 'numeric' };
const date = new Date('2013-03-10T02:00:00Z').toLocaleDateString('en-EN', options)
Check Date section for date options here https://www.w3schools.com/jsref/jsref_tolocalestring.asp
Pass your date in the date object:
var d = new Date('2013-03-10T02:00:00Z');
d.toLocaleDateString().replace(/\//g, '-');
If you have a date object:
let date = new Date()
let result = date.toISOString().split`T`[0]
console.log(result)
or
let date = new Date()
let result = date.toISOString().slice(0, 10)
console.log(result)
To extend on rk rk's solution: In case you want the format to include the time, you can add the toTimeString() to your string, and then strip the GMT part, as follows:
var d = new Date('2013-03-10T02:00:00Z');
var fd = d.toLocaleDateString() + ' ' + d.toTimeString().substring(0, d.toTimeString().indexOf("GMT"));
A better version of answer by #Hozefa.
If you have date-fns installed, you could use formatISO function
const date = new Date(2019, 0, 2)
import { formatISO } from 'date-fns'
formatISO(date, { representation: 'date' }) // '2019-01-02' string
If you have the timezone you can do:
const myDate = "2022-10-09T18:30:00.000Z"
const requestTimezone = "Asia/Calcutta";
const newDate = new Date(myDate).toLocaleString("en-CA", {
dateStyle: "short",
timeZone: requestTimezone,
});
console.log(newDate)
>> 2022-10-10
Another outputs:
const myDate = "2022-10-02T21:00:00.000Z"
const requestTimezone = "Asia/Jerusalem";
>> 2022-10-03
const myDate = "2022-09-28T04:00:00.000Z"
const requestTimezone = "America/New_York";
>> 2022-09-28
I used this:
HTMLDatetoIsoDate(htmlDate){
let year = Number(htmlDate.toString().substring(0, 4))
let month = Number(htmlDate.toString().substring(5, 7))
let day = Number(htmlDate.toString().substring(8, 10))
return new Date(year, month - 1, day)
}
isoDateToHtmlDate(isoDate){
let date = new Date(isoDate);
let dtString = ''
let monthString = ''
if (date.getDate() < 10) {
dtString = '0' + date.getDate();
} else {
dtString = String(date.getDate())
}
if (date.getMonth()+1 < 10) {
monthString = '0' + Number(date.getMonth()+1);
} else {
monthString = String(date.getMonth()+1);
}
return date.getFullYear()+'-' + monthString + '-'+dtString
}
Source: http://gooplus.fr/en/2017/07/13/angular2-typescript-isodate-to-html-date/
var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
alert(d.toLocaleDateString());
let dt = new Date('2013-03-10T02:00:00Z');
let dd = dt.getDate();
let mm = dt.getMonth() + 1;
let yyyy = dt.getFullYear();
if (dd<10) {
dd = '0' + dd;
}
if (mm<10) {
mm = '0' + mm;
}
return yyyy + '-' + mm + '-' + dd;
Many of these answers give potentially misleading output if one is looking for the day in the current timezone.
This function will output the day corresponding with the date's timezone offset:
const adjustDateToLocalTimeZoneDayString = (date?: Date) => {
if (!date) {
return undefined;
}
const dateCopy = new Date(date);
dateCopy.setTime(dateCopy.getTime() - dateCopy.getTimezoneOffset()*60*1000);
return dateCopy.toISOString().split('T')[0];
};
Tests:
it('return correct day even if timezone is included', () => {
// assuming the test is running in EDT timezone
// 11:34pm eastern time would be the next day in GMT
let result = adjustDateToLocalTimeZoneDayString(new Date('Wed Apr 06 2022 23:34:17 GMT-0400'));
// Note: This is probably what a person wants, the date in the current timezone
expect(result).toEqual('2022-04-06');
// 11:34pm zulu time should be the same
result = adjustDateToLocalTimeZoneDayString(new Date('Wed Apr 06 2022 23:34:17 GMT-0000'));
expect(result).toEqual('2022-04-06');
result = adjustDateToLocalTimeZoneDayString(undefined);
expect(result).toBeUndefined();
});
Misleading approach:
To demonstrate the issue with the other answers' direct ISOString().split() approach, note how the output below differs from what one might expect:
it('demonstrates how the simple ISOString().split() may be misleading', () => {
// Note this is the 7th
expect(new Date('Wed Apr 06 2022 23:34:17 GMT-0400').toISOString().split('T')[0]).toEqual('2022-04-07');
});
Simpler way to get Year Or Month
let isoDateTime = "2013-03-10T02:00:00Z";
console.log(isoDateTime.split("T")[0]); //2013-03-10
Using Split Method
console.log(isoDateTime.split("-")[0]); //2013
console.log(isoDateTime.split("-")[1]); //03
WARNING: Most of these answers are wrong.
That is because toISOString() always returns the UTC date, not local date. So, for example, if your UTC time is 0500 and your timezone is GMT-0800, the day returned by toISOString() will be the UTC day, which will be one day ahead of the local timezone day.
You need to first convert the date to the local date.
const date = new Date();
date.setTime(date.getTime() - date.getTimezoneOffset()*60*1000)
Now date.toISOString() will always return the proper date according to the local timezone.
But wait, there's more. If we are also using toTimeString() that will now be wrong because time is now local and toTimeString() assumes it is UTC and converts it. So we need to first extract toTimeString() as a variable before doing the conversion.
The Date() class in javascript is inconsistent because of this and should really be updated to avoid this confusion. The toISOString() and toTimeString() methods should both do the same default things with respect to timezone.
Use the below code. It is useful for you.
let currentDate = new Date()
currentDate.toISOString()

Categories

Resources