Related
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
I try to write a function to convert date and time from string to date. Here's my code:
var date_one = '2015-08-12 14:15:00';
var date_two = '2015-08-13 15:00:00';
console.log(date_one); //2015-08-12 14:15:00
console.log(date_two); //2015-08-13 15:00:00
var timeStamp_date_one = new Date(date_one).getTime() ; //NAN?
console.log(typeof timeStamp_date_one);//number
var timeStamp_date_two = new Date(date_two).getTime() ;//NAN?
console.log(typeof timeStamp_date_two);//number
//since you are having both datetime in numer time
//you can compare then to any logical oparation ( >, < ,= ,!= ,== ,!== ,>= AND <=)
//to be able to work with this date and time agin you need to convert it to an object
var newTime = new Date(timeStamp_date_one) ;
console.log(typeof newTime) ;//object
// you can the use this following function to convert your date and time to any format you want
console.log(DateAndTimeFormat(newTime , 'time')) ;// NaN:NaN ???
console.log(DateAndTimeFormat(newTime , 'date_time')) ;// NaN/NaN/NaN NaN:NaN ???
function DateAndTimeFormat(dateAndTime, type) {
switch (type) {
case 'time':
return dateAndTime.getHours() + ':' + (dateAndTime.getMinutes() < 10 ? '0' : '') +
dateAndTime.getMinutes()
case 'date':
return dateAndTime.getMonth() + 1 + '/' + dateAndTime.getDate() + '/' +
dateAndTime.getFullYear()
case 'date_time':
return dateAndTime.getMonth() + 1 + '/' + dateAndTime.getDate() + '/' +
dateAndTime.getFullYear() + ' ' + dateAndTime.getHours() + ':' +
(dateAndTime.getMinutes() < 10 ? '0' : '') + dateAndTime.getMinutes()
}
}
Why in this case I talways take a "Not-a-Number" value ? I expect that Object could be transfered to Data object like in this code. Somebody can told my why and how can I repair that code? Thank's a lot
As specified by https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date, when working with years like you are doing, the format is not "YYYY-MM-DD HH:MM:SS" but "YYYY-MM-DDTHH:MM:SS" (Notice the 'T' instead of the space)
var date_one = '2015-08-12T14:15:00';
var date_two = '2015-08-13T15:00:00';
With these values, your code works.
This is relative to the ISO 8601 standard
I would recommend to parse and split into chunks the string representing the date first and then use new Date(year, month, day, hour, minutes, seconds, milliseconds); constructor to be 100% sure there are no any local date format issues.
What is the best way to convert the following string to a javascript date string format of MM/DD/YYYY?
"25-AUG-11"
The best way is that given by jmeans in the comment to the question.
When given a string representing a date in one format, then the "best way" to covert it to another format is to first parse it to a date, then format the date to the string you want.
Unless this is a one-time conversion, don't waste your time writing code to format and parse dates! This is a solved problem that is implemented by many thoroughly tested libraries. If you are doing anything that involves date handling and computation, doing things on your own can be error-prone.
One good lightweight date library is moment.js.
Include moment.js like this:
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.0.0/moment.min.js"></script>
Then the JavaScript code for your particular example can be:
alert(moment("25-AUG-11", "DD-MMM-YY").format("MM/DD/YYYY"));
Live demo here
Note: Because you had "AUG" in your input string, you might need to tell the library to use English to parse the "MMM" part if your computer's locale does not use the English language.
Someday we will all speak ISO-8601. #rant :)
Use can use Date object method:
ToISOString()
This coverts date to string according to ISO standard
OR
Use :::toLocaleDateString()
You could use something like this:
var months={
"JAN":1,
"FEB":2,
//... other months
"DEC":12
}
var r=/(\d{1,2})\-(\w+)?\-(\d{1,2})/;
var replaceFunction=function(){
var years=parseInt(arguments[3],10);
var m=months[arguments[2]];
var days=arguments[1]
if(m<9){
m="0"+m;
}
if(days.length===1){
days="0"+days;
}
if(years>50){
years="19"+years;
}else{
years="20"+years;
}
return m+"/"+days+"/"+years;
};
console.log("5-JAN-14".replace(r,replaceFunction));
console.log("25-FEB-98".replace(r,replaceFunction));
You can use this JavaScript function to achieve that:
function formatDate(dateparam) {
var dateObj = new Date(Date.parse(dateparam));
var date = dateObj.getDate();
date = (date.toString().length == 1) ? "0" + date : date;
var month = dateObj.getMonth() + 1;
month = (month.toString().length == 1) ? "0" + month : month;
var year = dateObj.getFullYear();
return month + "/" + date + "/" + year;
}
document.write(formatDate("25-AUG-11"));
//returns "08/25/2011"
"Best" is relative and you haven't provided any criteria. Here's one way using plain string manipulation:
function reFormatDateString(s) {
s = s.split('-');
var months = {jan:'01', feb:'02', mar:'03', apr:'04', may:'05', jun:'06',
jul:'07', aug:'08', sep:'09', oct:'10', nov:'11', dec:'12'};
return months[s[1].toLowerCase()] + '/' + s[0] + '/' + s[2];
}
alert(reFormatDateString('25-AUG-11')); // 08/25/2011
However, likely you want to deal with the two digit year more specifically.
// The format "MM/DD/YYYY" isn't a "javascript" format, it's a US format.
function reFormatDateString1(s) {
s = s.split('-');
var months = {jan:'01', feb:'02', mar:'03', apr:'04', may:'05', jun:'06',
jul:'07', aug:'08', sep:'09', oct:'10', nov:'11', dec:'12'};
var m = +s[2];
s[2] = m < 100? (m < 50? m + 2000 : m + 1900) : m;
return months[s[1].toLowerCase()] + '/' + s[0] + '/' + s[2];
}
Here's another version that uses a date object:
function reFormatDateString2(s) {
s = s.split('-');
var months = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
function z(n){return (n<10? '0' : '') + n;}
// Convert 2 digit year. If < 50, assume 21st century,
// otherwise assume 20th.
// Adjust range to suit
if (s[2].length == 2) {
if (s[2] < 50 ) {
s[2] = +s[2] + 2000;
} else {
s[2] = +s[2] + 1900;
}
}
var d = new Date(s[2], months[s[1].toLowerCase()], s[0]);
return z(d.getMonth() + 1) + '/' + z(d.getMonth()+1) + '/' + z(d.getFullYear());
}
You choose "best".
This seems to be working fine.
var date = new Date("25-AUG-11");
console.log(date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear());
Working Fiddle
You just need to add 0 at starting of month value which can be done easily with string length comparison.
Source
I want to convert UTC time value (e.g.1367214805) to date (in dd-mm-yyyy) format using javascript.
For e.g. in PHP if we use...
<?php Date("d-m-Y",'1367214805'); ?>
... we directly get the date in dd-mm-yyyy format.
Is there any such function in javascript?
- I tried Date() in various ways in javascript but every time it is printing the present date and time!!
Thanks
JavaScript uses millisecond epoch, so you need to multiply your number by 1000.
var t = 1367214805;
var d = new Date(t * 1000);
There are then .getUTCxxx methods to get the fields you want, and then you can just zero pad and concatenate to get the required string.
function epochToDate(t) {
function pad2(n) {
return n > 9 ? n : '0' + n;
}
var d = new Date(t * 1000);
var year = d.getUTCFullYear();
var month = d.getUTCMonth() + 1; // months start at zero
var day = d.getUTCDate();
return pad2(day) + '-' + pad2(month) + '-' + year;
}
Take a look at Moments.js, you should be able to get whatever format you want and easily.
console.log(new Date());
console.log(moment().format("D-M-YY"));
console.log(moment(1367214805 * 1000).format("DD-MM-YY"));
jsfiddle
You could use toISOString method and just ignore everything after the T e.g.
var isoDateStr = myDate.toISOString();
isoDateStr = isoDateStr.substring(0, isoDateStr.indexOf('T'));
This would give you standard UTC date format yyyy-mm-dd. If you need to specifically format the date as dd-mm-yyyy then you can take that result and switch the values i.e.
isoDateStr = isoDateStr.split('-').reverse().join('-');
You can try this:
myDate.toISOString().split('T')[0].split('-').reverse().join('-')
Why not use getUTCxxx() methods?
function formatUTC(time_UTC_in_milliseconds_since_epoch) {
/*
* author: WesternGun
*/
var time = new Date(time_UTC_in_milliseconds_since_epoch);
var formatted = time.getUTCFullYear() + "-"
+ (time.getUTCMonth() + 1).toString() + "-"
+ time.getUTCDate() + " "
+ time.getUTCHours() + ":"
+ time.getUTCMinutes() + ":"
+ time.getUTCSeconds();
return formatted;
}
Remember to add 1 to the month because the range of return value of getUTCMonth() is 0~11.
With your input, we have:
formatUTC(1367214805 * 1000); // return "2013-4-29 5:53:25"
To format the numbers into \d\d form, just create another function:
function normalizeNumber(input, toAdd) {
if (parseInt(input) < 10) {
return toAdd + input;
} else {
return input;
}
}
And use it like normalizeNumber((time.getUTCMonth() + 1).toString(), "0"), etc.
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