Force browser to display all dates to specific timezone [duplicate] - javascript

This question already has answers here:
Convert date to another timezone in JavaScript
(34 answers)
How to initialize a JavaScript Date to a particular time zone
(20 answers)
Closed 9 years ago.
How can I force Browser to display all date objects to use Specific Timezone.Like passing Europe/London.Is there any way to do so??
Update
Here I want is that all Jquery Datepicker open date and time as per Specific Timezone instead of Client's Machine.

You can't "set" the timezone offset, it's a read only property that is based on system settings.
You can generate time and date values for any timezone offset by simply adding the client timezone offset, then adding whatever offset you want (note that javascript Date object's timezone offset has an opposite sense to the usual value, so you add both rather than subtracting one and adding the other).
e.g.
// Provide offsetInMintes to add to UTC to get required time,
// e.g. Nepal Standard Time is UTC +05:45 -> +345 minutes
function generateOffsetTime(offsetInMinutes) {
function z(n){return (n<10? '0' : '') + n;}
var d = new Date();
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + offsetInMinutes);
return [z(d.getHours()),z(d.getMinutes()),z(d.getSeconds())].join(':');
}
alert('The time in Nepal is ' + generateOffsetTime(345));
Edit
You could add your own methods to Date.prototype:
Date.prototype.setOffset = function(offsetInMinutes, offsetName) {
this._offsetInMinutes = offsetInMinutes;
this._offsetName = offsetName;
};
Date.prototype.getOffsetFullDate = (function() {
var months = ('January February March April May June July ' +
'August September October November December').split(' ');
var days = 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday'.split(' ');
return function() {
var d = new Date(+this);
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + this._offsetInMinutes);
return days[d.getDay()] + ' ' + d.getDate() + ' ' + months[d.getMonth()] +
', ' + this.getFullYear();
}
}());
Date.prototype.getOffsetTime = (function() {
function z(n){return (n<10? '0' : '') + n;}
return function() {
var d = new Date(+this);
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + this._offsetInMinutes);
return z(d.getHours()) + ':' + z(d.getMinutes()) + ':' +
z(d.getSeconds()) + ' ' + this._offsetName;
}
}());
var d = new Date();
d.setOffset(345, 'NST')
console.log(d.getOffsetFullDate() + ' ' + d.getOffsetTime());
Note that this keeps the date object's original timevalue, it adjusts values as they are retrieved so the timezone can be changed to get different values for the same date object, so you could continue with:
d.setOffset(600, 'AEST');
console.log(d.getOffsetFullDate() + ' ' + d.getOffsetTime());
d.setOffset(630, 'LHI');
console.log(d.getOffsetFullDate() + ' ' + d.getOffsetTime());
But I still think it's better to build your own date constructor that leverages the built in Date rather than extends it.

Moment.js is a great library which could help you to achieve this.

Related

Convert UTC to current timezone in javascript

I have time as 2023-02-01T17:00:22.127Z which is in UTC. I want to convert this to the timezone of the user from where user is logged in. How can I do this using javascript?
I was trying to use https://yarnpkg.com/package/jstz but couldn’t use a way to convert the time. Please help resolve this issue
Here is a function that converts a UTC date string to a local browser date string with format YYYY-MM-DD hh:MM:
function getLocalDateString(utcStr) {
const date = new Date(utcStr);
return date.getFullYear()
+ '-' + String(date.getMonth() + 1).padStart(2, '0')
+ '-' + String(date.getDate()).padStart(2, '0')
+ ' ' + String(date.getHours()).padStart(2, '0')
+ ':' + String(date.getMinutes()).padStart(2, '0');
}
console.log({
'2023-02-01T00:55:22.127Z': getLocalDateString('2023-02-01T00:55:22.127Z'),
'2023-02-01T17:00:22.127Z': getLocalDateString('2023-02-01T17:00:22.127Z')
});
Ouput in my timezone:
{
"2023-02-01T00:55:22.127Z": "2023-01-31 16:55",
"2023-02-01T17:00:22.127Z": "2023-02-01 09:00"
}

Convert stringDate to new Date() and back again in same format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I've got multiple dictionaries with dates in and I need to find the highest one. To compare the dates I get the date from the dictionary, convert it using new Date(dateString) to be able to compare the dates to get the latest date.
The dateString looks like this: 2019-03-07 08:40:16
I convert this using new Date(dateString) and it looks like this:
Thu Mar 07 2019 08:40:16 GMT+0000 (Greenwich Mean Time)
I then need to convert it back to original format YYYY-MM-DD HH:MM:SS
What is the best way to do this, I thought there would be something where you could define the output format for new Date() but can't find anything.
Any help is appreciated.
I'd recommend you to use Moment https://momentjs.com/ lib for time comparison and formatting.
const date1 = moment('2019-03-06 08:40:16', 'YYYY-MM-DD HH:mm:ss');
const date2 = moment('2019-03-07 08:40:16', 'YYYY-MM-DD HH:mm:ss');
const isBefore = date1.isBefore(date2);
console.log('isBefore', isBefore);
console.log('formatted date:', date2.format('YYYY-MM-DD HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
This is surely ain't the most elegant solution but based on the conversion from dateString, you can reconstruct it using the Date() objects built-in methods.
var dateString = "2019-03-07 08:40:16";
var temp = new Date(dateString);
var temp2 = "" + temp.getFullYear() + "-" + (temp.getMonth() + 1) + "-" + temp.getDate() + " " + temp.getHours() + ":" + temp.getMinutes() + ":" + temp.getSeconds();
console.log(temp2);
If you plan to do this with multiple dates, you might consider enhancing the Date object with your own method like:
Date.prototype.reformat = function() {
return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate() + " " + this.getHours() + ":" + this.getMinutes() + "." + this.getSeconds();
}
var dateString = "2019-03-07 08:40:16";
var temp = new Date(dateString);
console.log(temp.reformat());

Displaying a field with ISODate not Local Date [duplicate]

I have a Date object. How do I render the title portion of the following snippet?
<abbr title="2010-04-02T14:12:07">A couple days ago</abbr>
I have the "relative time in words" portion from another library.
I've tried the following:
function isoDate(msSinceEpoch) {
var d = new Date(msSinceEpoch);
return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T' +
d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}
But that gives me:
"2010-4-2T3:19"
There is already a function called toISOString():
var date = new Date();
date.toISOString(); //"2011-12-19T15:28:46.493Z"
If, somehow, you're on a browser that doesn't support it, I've got you covered:
if (!Date.prototype.toISOString) {
(function() {
function pad(number) {
var r = String(number);
if (r.length === 1) {
r = '0' + r;
}
return r;
}
Date.prototype.toISOString = function() {
return this.getUTCFullYear() +
'-' + pad(this.getUTCMonth() + 1) +
'-' + pad(this.getUTCDate()) +
'T' + pad(this.getUTCHours()) +
':' + pad(this.getUTCMinutes()) +
':' + pad(this.getUTCSeconds()) +
'.' + String((this.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5) +
'Z';
};
}());
}
console.log(new Date().toISOString())
Note: This answer is still getting upvotes as of 2022-03. The moment.js library is deprecated. These are the two main alternatives: Luxon and Day.js, others are mentioned in the deprecation link.
Luxon
Luxon can be thought of as the evolution of Moment. It is authored by
Isaac Cambron, a long-time contributor to Moment. Please read Why does
Luxon exist? and the For Moment users pages in the Luxon
documentation.
Locales: Intl provided Time Zones: Intl provided
Day.js
Day.js is designed to be a minimalist replacement for Moment.js, using
a similar API. It is not a drop-in replacement, but if you are used to
using Moment's API and want to get moving quickly, consider using
Day.js.
Locales: Custom data files that can be individually imported Time
Zones: Intl provided, via a plugin
I use Day.js because of the size difference, but Luxon is easier to deal with.
Almost every to-ISO method on the web drops the timezone information by applying a convert to "Z"ulu time (UTC) before outputting the string. Browser's native .toISOString() also drops timezone information.
This discards valuable information, as the server, or recipient, can always convert a full ISO date to Zulu time or whichever timezone it requires, while still getting the timezone information of the sender.
The best solution I've come across is to use the Moment.js javascript library and use the following code:
To get the current ISO time with timezone information and milliseconds
now = moment().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T20:11:11.234+0100"
now = moment().utc().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T19:11:11.234+0000"
now = moment().utc().format("YYYY-MM-DDTHH:mm:ss") + "Z"
// "2013-03-08T19:11:11Z" <- better use the native .toISOString()
To get the ISO time of a native JavaScript Date object with timezone information but without milliseconds
var current_time = Date.now();
moment(current_time).format("YYYY-MM-DDTHH:mm:ssZZ")
This can be combined with Date.js to get functions like Date.today() whose result can then be passed to moment.
A date string formatted like this is JSON compilant, and lends itself well to get stored into a database. Python and C# seem to like it.
See the last example on page https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date:
/* Use a function for the exact format desired... */
function ISODateString(d) {
function pad(n) {return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
console.log(ISODateString(d)); // Prints something like 2009-09-28T19:03:12Z
The question asked was ISO format with reduced precision. Voila:
new Date().toISOString().slice(0, 19) + 'Z'
// '2014-10-23T13:18:06Z'
Assuming the trailing Z is wanted, otherwise just omit.
Shortest, but not supported by Internet Explorer 8 and earlier:
new Date().toJSON()
If you don't need to support IE7, the following is a great, concise hack:
console.log(
JSON.parse(JSON.stringify(new Date()))
)
I typically don't want to display a UTC date since customers don't like doing the conversion in their head. To display a local ISO date, I use the function:
function toLocalIsoString(date, includeSeconds) {
function pad(n) { return n < 10 ? '0' + n : n }
var localIsoString = date.getFullYear() + '-'
+ pad(date.getMonth() + 1) + '-'
+ pad(date.getDate()) + 'T'
+ pad(date.getHours()) + ':'
+ pad(date.getMinutes()) + ':'
+ pad(date.getSeconds());
if(date.getTimezoneOffset() == 0) localIsoString += 'Z';
return localIsoString;
};
The function above omits time zone offset information (except if local time happens to be UTC), so I use the function below to show the local offset in a single location. You can also append its output to results from the above function if you wish to show the offset in each and every time:
function getOffsetFromUTC() {
var offset = new Date().getTimezoneOffset();
return ((offset < 0 ? '+' : '-')
+ pad(Math.abs(offset / 60), 2)
+ ':'
+ pad(Math.abs(offset % 60), 2))
};
toLocalIsoString uses pad. If needed, it works like nearly any pad function, but for the sake of completeness this is what I use:
// Pad a number to length using padChar
function pad(number, length, padChar) {
if (typeof length === 'undefined') length = 2;
if (typeof padChar === 'undefined') padChar = '0';
var str = "" + number;
while (str.length < length) {
str = padChar + str;
}
return str;
}
The problem with toISOString is that it gives datetime only as "Z".
ISO-8601 also defines datetime with timezone difference in hours and minutes, in the forms like 2016-07-16T19:20:30+5:30 (when timezone is ahead UTC) and 2016-07-16T19:20:30-01:00 (when timezone is behind UTC).
I don't think it is a good idea to use another plugin, moment.js for such a small task, especially when you can get it with a few lines of code.
Once you have the timezone offset in hours and minutes, you can append to a datetime string.
I wrote a blog post on it : http://usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-minutes
var timezone_offset_min = new Date().getTimezoneOffset(),
offset_hrs = parseInt(Math.abs(timezone_offset_min / 60)),
offset_min = Math.abs(timezone_offset_min % 60),
timezone_standard;
if (offset_hrs < 10)
offset_hrs = '0' + offset_hrs;
if (offset_min > 10)
offset_min = '0' + offset_min;
// getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and vice-versa.
// So add an opposite sign to the offset
// If offset is 0, it means timezone is UTC
if (timezone_offset_min < 0)
timezone_standard = '+' + offset_hrs + ':' + offset_min;
else if (timezone_offset_min > 0)
timezone_standard = '-' + offset_hrs + ':' + offset_min;
else if (timezone_offset_min == 0)
timezone_standard = 'Z';
// Timezone difference in hours and minutes
// String such as +5:30 or -6:00 or Z
console.log(timezone_standard);
There is a '+' missing after the 'T'
isoDate: function(msSinceEpoch) {
var d = new Date(msSinceEpoch);
return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T'
+ d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}
should do it.
For the leading zeros you could use this from here:
function PadDigits(n, totalDigits)
{
n = n.toString();
var pd = '';
if (totalDigits > n.length)
{
for (i=0; i < (totalDigits-n.length); i++)
{
pd += '0';
}
}
return pd + n.toString();
}
Using it like this:
PadDigits(d.getUTCHours(),2)
function timeStr(d) {
return ''+
d.getFullYear()+
('0'+(d.getMonth()+1)).slice(-2)+
('0'+d.getDate()).slice(-2)+
('0'+d.getHours()).slice(-2)+
('0'+d.getMinutes()).slice(-2)+
('0'+d.getSeconds()).slice(-2);
}
I was able to get below output with very less code.
var ps = new Date('2010-04-02T14:12:07') ;
ps = ps.toDateString() + " " + ps.getHours() + ":"+ ps.getMinutes() + " hrs";
Output:
Fri Apr 02 2010 19:42 hrs
I think I have found an even better solution:
According to the wiki page Canada uses ISO 8601 as the official date format, therefore we can safely use this.
console.log(new Date("2022-12-19 00:43:00 GMT+0100").toISOString().split("T")[0]);
// results in '2022-12-18'
console.log(new Date("2022-12-19 00:43:00 GMT+0100").toLocaleDateString("en-CA"));
// results in '2022-12-19'
I would just use this small extension to Date - http://blog.stevenlevithan.com/archives/date-time-format
var date = new Date(msSinceEpoch);
date.format("isoDateTime"); // 2007-06-09T17:46:21
function getdatetime() {
d = new Date();
return (1e3-~d.getUTCMonth()*10+d.toUTCString()+1e3+d/1)
.replace(/1(..)..*?(\d+)\D+(\d+).(\S+).*(...)/,'$3-$1-$2T$4.$5Z')
.replace(/-(\d)T/,'-0$1T');
}
I found the basics on Stack Overflow somewhere (I believe it was part of some other Stack Exchange code golfing), and I improved it so it works on Internet Explorer 10 or earlier as well. It's ugly, but it gets the job done.
A short one:
console.log(new Date().toISOString().slice(0,19).replace('T', ' '))
To extend Sean's great and concise answer with some sugar and modern syntax:
// date.js
const getMonthName = (num) => {
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Oct', 'Nov', 'Dec'];
return months[num];
};
const formatDate = (d) => {
const date = new Date(d);
const year = date.getFullYear();
const month = getMonthName(date.getMonth());
const day = ('0' + date.getDate()).slice(-2);
const hour = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
return `${year} ${month} ${day}, ${hour}:${minutes}`;
};
module.exports = formatDate;
Then eg.
import formatDate = require('./date');
const myDate = "2018-07-24T13:44:46.493Z"; // Actual value from wherever, eg. MongoDB date
console.log(formatDate(myDate)); // 2018 Jul 24, 13:44

User current time

I have a script that stores an action taken by a user. There's a column that contains datetime and originally I user NOW(), but that uses server time, which is a few hours off as compared to the user's actual time.
So I decided I'll use the time that I can get with JS. I've formatted it this way:
var now = new Date(),
isnow = now.getFullYear() + '-' + ('0' + (now.getMonth() + 1)).slice(-2) + '-' + ('0' + now.getDate()).slice(-2) + ' ' + ('0' + (now.getHours() + 1)).slice(-2) + ':' + ('0' + now.getMinutes()).slice(-2) + ':' + ('0' + now.getSeconds()).slice(-2);
I've tested and while the format works fine, the time is off by an hour. Is it because of the Daylight Savings Time? How do I get the actual local time for the user?
In your code wrote:
...('0' + (now.getHours() + 1)).slice(-2)...
Try to remove this plus one
Additional you can check if Day Savings Time with:
if (now.dst()) { alert ("Daylight savings time!"); }
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
Based at answer similar issue
You should use the toISOString() method to convert the Date object to the ISO-8601 standard format:
now.toISOString();
The ISO-8601 date format puts the time information into a universal form which includes optional timezone information (likely the source of your issues).

How do I output an ISO 8601 formatted string in JavaScript?

I have a Date object. How do I render the title portion of the following snippet?
<abbr title="2010-04-02T14:12:07">A couple days ago</abbr>
I have the "relative time in words" portion from another library.
I've tried the following:
function isoDate(msSinceEpoch) {
var d = new Date(msSinceEpoch);
return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T' +
d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}
But that gives me:
"2010-4-2T3:19"
There is already a function called toISOString():
var date = new Date();
date.toISOString(); //"2011-12-19T15:28:46.493Z"
If, somehow, you're on a browser that doesn't support it, I've got you covered:
if (!Date.prototype.toISOString) {
(function() {
function pad(number) {
var r = String(number);
if (r.length === 1) {
r = '0' + r;
}
return r;
}
Date.prototype.toISOString = function() {
return this.getUTCFullYear() +
'-' + pad(this.getUTCMonth() + 1) +
'-' + pad(this.getUTCDate()) +
'T' + pad(this.getUTCHours()) +
':' + pad(this.getUTCMinutes()) +
':' + pad(this.getUTCSeconds()) +
'.' + String((this.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5) +
'Z';
};
}());
}
console.log(new Date().toISOString())
Note: This answer is still getting upvotes as of 2022-03. The moment.js library is deprecated. These are the two main alternatives: Luxon and Day.js, others are mentioned in the deprecation link.
Luxon
Luxon can be thought of as the evolution of Moment. It is authored by
Isaac Cambron, a long-time contributor to Moment. Please read Why does
Luxon exist? and the For Moment users pages in the Luxon
documentation.
Locales: Intl provided Time Zones: Intl provided
Day.js
Day.js is designed to be a minimalist replacement for Moment.js, using
a similar API. It is not a drop-in replacement, but if you are used to
using Moment's API and want to get moving quickly, consider using
Day.js.
Locales: Custom data files that can be individually imported Time
Zones: Intl provided, via a plugin
I use Day.js because of the size difference, but Luxon is easier to deal with.
Almost every to-ISO method on the web drops the timezone information by applying a convert to "Z"ulu time (UTC) before outputting the string. Browser's native .toISOString() also drops timezone information.
This discards valuable information, as the server, or recipient, can always convert a full ISO date to Zulu time or whichever timezone it requires, while still getting the timezone information of the sender.
The best solution I've come across is to use the Moment.js javascript library and use the following code:
To get the current ISO time with timezone information and milliseconds
now = moment().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T20:11:11.234+0100"
now = moment().utc().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
// "2013-03-08T19:11:11.234+0000"
now = moment().utc().format("YYYY-MM-DDTHH:mm:ss") + "Z"
// "2013-03-08T19:11:11Z" <- better use the native .toISOString()
To get the ISO time of a native JavaScript Date object with timezone information but without milliseconds
var current_time = Date.now();
moment(current_time).format("YYYY-MM-DDTHH:mm:ssZZ")
This can be combined with Date.js to get functions like Date.today() whose result can then be passed to moment.
A date string formatted like this is JSON compilant, and lends itself well to get stored into a database. Python and C# seem to like it.
See the last example on page https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date:
/* Use a function for the exact format desired... */
function ISODateString(d) {
function pad(n) {return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
console.log(ISODateString(d)); // Prints something like 2009-09-28T19:03:12Z
The question asked was ISO format with reduced precision. Voila:
new Date().toISOString().slice(0, 19) + 'Z'
// '2014-10-23T13:18:06Z'
Assuming the trailing Z is wanted, otherwise just omit.
Shortest, but not supported by Internet Explorer 8 and earlier:
new Date().toJSON()
If you don't need to support IE7, the following is a great, concise hack:
console.log(
JSON.parse(JSON.stringify(new Date()))
)
I typically don't want to display a UTC date since customers don't like doing the conversion in their head. To display a local ISO date, I use the function:
function toLocalIsoString(date, includeSeconds) {
function pad(n) { return n < 10 ? '0' + n : n }
var localIsoString = date.getFullYear() + '-'
+ pad(date.getMonth() + 1) + '-'
+ pad(date.getDate()) + 'T'
+ pad(date.getHours()) + ':'
+ pad(date.getMinutes()) + ':'
+ pad(date.getSeconds());
if(date.getTimezoneOffset() == 0) localIsoString += 'Z';
return localIsoString;
};
The function above omits time zone offset information (except if local time happens to be UTC), so I use the function below to show the local offset in a single location. You can also append its output to results from the above function if you wish to show the offset in each and every time:
function getOffsetFromUTC() {
var offset = new Date().getTimezoneOffset();
return ((offset < 0 ? '+' : '-')
+ pad(Math.abs(offset / 60), 2)
+ ':'
+ pad(Math.abs(offset % 60), 2))
};
toLocalIsoString uses pad. If needed, it works like nearly any pad function, but for the sake of completeness this is what I use:
// Pad a number to length using padChar
function pad(number, length, padChar) {
if (typeof length === 'undefined') length = 2;
if (typeof padChar === 'undefined') padChar = '0';
var str = "" + number;
while (str.length < length) {
str = padChar + str;
}
return str;
}
The problem with toISOString is that it gives datetime only as "Z".
ISO-8601 also defines datetime with timezone difference in hours and minutes, in the forms like 2016-07-16T19:20:30+5:30 (when timezone is ahead UTC) and 2016-07-16T19:20:30-01:00 (when timezone is behind UTC).
I don't think it is a good idea to use another plugin, moment.js for such a small task, especially when you can get it with a few lines of code.
Once you have the timezone offset in hours and minutes, you can append to a datetime string.
I wrote a blog post on it : http://usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-minutes
var timezone_offset_min = new Date().getTimezoneOffset(),
offset_hrs = parseInt(Math.abs(timezone_offset_min / 60)),
offset_min = Math.abs(timezone_offset_min % 60),
timezone_standard;
if (offset_hrs < 10)
offset_hrs = '0' + offset_hrs;
if (offset_min > 10)
offset_min = '0' + offset_min;
// getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and vice-versa.
// So add an opposite sign to the offset
// If offset is 0, it means timezone is UTC
if (timezone_offset_min < 0)
timezone_standard = '+' + offset_hrs + ':' + offset_min;
else if (timezone_offset_min > 0)
timezone_standard = '-' + offset_hrs + ':' + offset_min;
else if (timezone_offset_min == 0)
timezone_standard = 'Z';
// Timezone difference in hours and minutes
// String such as +5:30 or -6:00 or Z
console.log(timezone_standard);
There is a '+' missing after the 'T'
isoDate: function(msSinceEpoch) {
var d = new Date(msSinceEpoch);
return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T'
+ d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}
should do it.
For the leading zeros you could use this from here:
function PadDigits(n, totalDigits)
{
n = n.toString();
var pd = '';
if (totalDigits > n.length)
{
for (i=0; i < (totalDigits-n.length); i++)
{
pd += '0';
}
}
return pd + n.toString();
}
Using it like this:
PadDigits(d.getUTCHours(),2)
function timeStr(d) {
return ''+
d.getFullYear()+
('0'+(d.getMonth()+1)).slice(-2)+
('0'+d.getDate()).slice(-2)+
('0'+d.getHours()).slice(-2)+
('0'+d.getMinutes()).slice(-2)+
('0'+d.getSeconds()).slice(-2);
}
I was able to get below output with very less code.
var ps = new Date('2010-04-02T14:12:07') ;
ps = ps.toDateString() + " " + ps.getHours() + ":"+ ps.getMinutes() + " hrs";
Output:
Fri Apr 02 2010 19:42 hrs
I think I have found an even better solution:
According to the wiki page Canada uses ISO 8601 as the official date format, therefore we can safely use this.
console.log(new Date("2022-12-19 00:43:00 GMT+0100").toISOString().split("T")[0]);
// results in '2022-12-18'
console.log(new Date("2022-12-19 00:43:00 GMT+0100").toLocaleDateString("en-CA"));
// results in '2022-12-19'
I would just use this small extension to Date - http://blog.stevenlevithan.com/archives/date-time-format
var date = new Date(msSinceEpoch);
date.format("isoDateTime"); // 2007-06-09T17:46:21
function getdatetime() {
d = new Date();
return (1e3-~d.getUTCMonth()*10+d.toUTCString()+1e3+d/1)
.replace(/1(..)..*?(\d+)\D+(\d+).(\S+).*(...)/,'$3-$1-$2T$4.$5Z')
.replace(/-(\d)T/,'-0$1T');
}
I found the basics on Stack Overflow somewhere (I believe it was part of some other Stack Exchange code golfing), and I improved it so it works on Internet Explorer 10 or earlier as well. It's ugly, but it gets the job done.
A short one:
console.log(new Date().toISOString().slice(0,19).replace('T', ' '))
To extend Sean's great and concise answer with some sugar and modern syntax:
// date.js
const getMonthName = (num) => {
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Oct', 'Nov', 'Dec'];
return months[num];
};
const formatDate = (d) => {
const date = new Date(d);
const year = date.getFullYear();
const month = getMonthName(date.getMonth());
const day = ('0' + date.getDate()).slice(-2);
const hour = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
return `${year} ${month} ${day}, ${hour}:${minutes}`;
};
module.exports = formatDate;
Then eg.
import formatDate = require('./date');
const myDate = "2018-07-24T13:44:46.493Z"; // Actual value from wherever, eg. MongoDB date
console.log(formatDate(myDate)); // 2018 Jul 24, 13:44

Categories