Extract time from JS Date object without offsetting the Time zone - javascript

So we have multiple clients, that are in multiple time zones. I'm pulling some dates from an API, and the dates/times that are in this string are exactly what I need to display. I've been researching this, and digging for some time, and still haven't come up with a clear answer. The string coming in is formatted as such:
"2017-12-29T20:00:00"
What I'm wanting is to extract both the date and time as is, into two strings (no timezone offsetting, no matter where the viewer is located) but am having some issues doing so. Also hoping to format it in the correct fashion as well. Example:
"M/d/yyyy"
"hh:mm AM/PM" (12 hour)
I've tried numerous ways to battle this, and don't really want to just grab substrings, but am half tempted to do so. Any help is appreciated.

Consider just reformatting the string, it avoids all issues with the built-in parser and timezones:
function reformatTimestamp(s) {
function z(n){return (n<10?'0':'')+ +n}
var b = s.split(/\D/);
var h = b[3]%12 || 12;
var ap = b[3] < 12? 'AM':'PM';
return b[1] + '/' + b[2] + '/' + b[0] +
' ' + z(h) + ':' + z(b[4]) + ' ' + ap;
}
console.log(reformatTimestamp('2017-12-29T20:00:00')) // 12/29/2017 08:00 PM
I think it would be better to pad the month and day with a leading zero (but I'd also use an unambiguous date format like DD-MMM-YYYY rather than the peculiar m/d/y).

Use this code:
function formatAMPM(date) {
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
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;
}
var str = "2017-12-29T20:00:00";
var dt = new Date(str + "Z");
console.log("M/d/yyyy");
console.log((dt.getUTCMonth() + 1) + '/' + dt.getUTCDate() + '/' + dt.getUTCFullYear());
console.log("hh:mm AM/PM");
console.log(formatAMPM(dt));

Related

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

Best way to convert a unix timestamp to javascript date-time

I have been following Convert a Unix timestamp to time in JavaScript thread for answer but looks like single digit time (0-9) is parsed as it is. The accepted answer
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
We get like 2:3:9 instead of 02:03:09. How to get rid of this behaviour? Also can anyone please elaborate on how to get am/pm along with time?
var formattedTime = ('0' + hours).substr(-2) + ':'
+ ('0' + minutes).substr(-2) + ':'
+ ('0' + seconds).substr(-2);
I think I will leave the am:pm bit to you. Press ctrl-shift j and play with your code in the console right here
// /*Year m-1 d h m s ms*/
unix_timestamp = Math.floor(new Date(2016,0, 1,5,5,0,0)/1000)
This might be easier to understand. I have kept it closer
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var amPm = date.getHours() >= 12?'AM':'PM'
// % is modulo which is the remainder after division || will change 0 to 12
// because 0 is falsey everything else will be left as it is
var hours = ("0" + ((date.getHours() % 12)||12)).substr(-2)
// Minutes part from the timestamp
var minutes = ("0" + date.getMinutes()).substr(-2)
// Seconds part from the timestamp
var seconds = ("0" + date.getSeconds()).substr(-2)
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes+ ':' + seconds + ' '+ amPm
I think you have to get rid of the substr-part, since the value should already be correct.
Note: you need to check if the values are already above 9, because you don't need to append anything when it is above 9.
Example
var d = new Date() //Is in milliseconds
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
console.log(hours + ":" + ((minutes < 10) ? "0" + minutes : minutes) + ":" + ((seconds < 10) ? "0" + seconds : seconds))
I want to add that these kinds of problems can be easily resolved with using a good library like moment.js

Is there a way to directly format the time in Javascript?

What I want it is to get the output of the current time with Javascript. The output should be something similar as:
15:28:30 PM
And I got this using the following code:
var date = new Date();
document.write("Current time: " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds());
if (date.getHours() <= 12)
document.write(" AM");
else
document.write(" PM");
So the output that I get it is:
Current time: 3:0:16 AM
But I want to know if there is some faster or cleaner solution to solve this problem because I think my solution it is not good at all.
Is it possible to get the same behaviour with a better method or solution?
Thanks in advance!
var date = new Date();
var time = date.toLocaleString('en').split(', ').pop();
This will give you the exact format you are looking for. Although I would go with a library like Moment.js or Date.js. Tons of options with those.
It's like this:
var dt = new Date;
console.log(dt.toLocaleTimeString());
I see nothing wrong with your approach. However, if you want the flexibility of different formats, there's a library called moment.js which allows you to build and format dates.
moment().format('hh:mm:ss A'); // 12:00:00 AM
I think that you make right way. Only need modify a little to get your expectation:
var date = new Date();
int hour = date.getHours();
string abbr;
if (date.getHours() <= 12)
abbr = " AM";
else {
hour = hour + 12;
abbr = " PM";
}
document.write("Current time: " + hour + ":" + date.getMinutes() + ":" + date.getSeconds() + abbr);
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10) {
minutes = "0" + minutes
}
if (seconds < 10) {
seconds = "0" + seconds
}
str += hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
str += "PM"
} else {
str += "AM"
}
return str;
}
Found this thread

Remove trailing zeroes in date in JavaScript

I am using the current format in order to product a JavaScript date:
var date = visitdate;
var newdate = date.split("/").reverse().join("-");
I would expect this to return 1900-01-01 for example, however what this actually returns is 1900-01-0100.
Iv'e tried using slice in order to trim this off but this just ends up slicing off the day instead and still adds the zeros. There seems to be no way of getting rid of them. Is there anyway to remove them?
You may write a function like below and whatever format needed you can change
function formatDate(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'
hours = hours < 10 ? '0'+hours : hours;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
var Month = date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1;
var Date = date.getDate() < 10 ? '0'+date.getDate() : date.getDate();
var strDate = Month + "/" + Date + "/" + date.getFullYear();
return strDate + " " + strTime;
}
Or in your case if you dont want time just remove strTime from return of function
Assuming the input is "01/01/1900 00:00" - add a .split(" ") in between like this:
"01/01/1900 00:00".split(" ")[0].split("/").reverse().join("-");
Or just skip the reverse() if your input is like you said "1900-01-01":
"1900/01/01 00:00".split(" ")[0].split("/").join("-");
You could also extract the information from your date string by using a regex like this:
var d = '1990/01/01 00:00';
var matches = d.match(/^(\d+)\/(\d+)\/(\d+) (\d+):(\d+)$/);
if(matches){
var year = matches[1]
, month = matches[2]
, day = matches[3]
, hour = matches[4]
, minutes = matches[5];
console.log(year+'-'+month+'-'+day);
}

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