[Addendum 12/2022]: Here's a library to format dates using Intl.DateTimeFormat.
[Addendum 01/2024]: And here is a (ES-)Date manipulation library
Try something like this
var d = new Date,
dformat = [d.getMonth()+1,
d.getDate(),
d.getFullYear()].join('/')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
If you want leading zero's for values < 10, use this number extension
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3'
Applied to the previous code:
var d = new Date,
dformat = [(d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/') +' ' +
[d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'
See this code in [jsfiddle][1]
[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.
const dt = new Date();
const padL = (nr, len = 2, chr = `0`) => `${nr}`.padStart(2, chr);
console.log(`${
padL(dt.getMonth()+1)}/${
padL(dt.getDate())}/${
dt.getFullYear()} ${
padL(dt.getHours())}:${
padL(dt.getMinutes())}:${
padL(dt.getSeconds())}`
);
Answer from KooiInc on Stack Overflow[Addendum 12/2022]: Here's a library to format dates using Intl.DateTimeFormat.
[Addendum 01/2024]: And here is a (ES-)Date manipulation library
Try something like this
var d = new Date,
dformat = [d.getMonth()+1,
d.getDate(),
d.getFullYear()].join('/')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');
If you want leading zero's for values < 10, use this number extension
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3'
Applied to the previous code:
var d = new Date,
dformat = [(d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/') +' ' +
[d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'
See this code in [jsfiddle][1]
[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.
const dt = new Date();
const padL = (nr, len = 2, chr = `0`) => `${nr}`.padStart(2, chr);
console.log(`${
padL(dt.getMonth()+1)}/${
padL(dt.getDate())}/${
dt.getFullYear()} ${
padL(dt.getHours())}:${
padL(dt.getMinutes())}:${
padL(dt.getSeconds())}`
);
You can always format a date by extracting the parts and combine them using string functions in desired order:
function formatDate(date) {
let datePart = [
date.getMonth() + 1,
date.getDate(),
date.getFullYear()
].map((n, i) => n.toString().padStart(i === 2 ? 4 : 2, "0")).join("/");
let timePart = [
date.getHours(),
date.getMinutes(),
date.getSeconds()
].map((n, i) => n.toString().padStart(2, "0")).join(":");
return datePart + " " + timePart;
}
let date = new Date();
console.log("%o => %s", date, formatDate(date));
Videos
Call the toISOString() method:
var dt = new Date("30 July 2010 15:05 UTC");
document.write(dt.toISOString());
// Output:
// 2010-07-30T15:05:00.000Z
toISOString() will return current UTC time only not the current local time. If you want to get the current local time in yyyy-MM-ddTHH:mm:ss.SSSZ format then you should get the current time using following two methods
Method 1:
console.log(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString());
Method 2:
console.log(new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString());
Hey sorry about the moment.js link. when i went to CDN i accidentally clicked on the wrong script link. I have updated my Comment.
Also for an example of both conversion methods i have made a fiddle Here Edit fiddle - JSFiddle - Code Playground In this example it shows how to convert with both Moment and the pure JS method I put in my first post. If your not familiar with Fiddle its a good place to test code quickly. Good Luck!
P.S.
I have also updated my original comment as the error in my Code was due to not converting the Date Object back to a string before slicing it.
I have a javascript file that I need to modify to take a date (field sold_at) and convert it to a simpler format.Currently it is in standard YYYY-MM-DD HH:MM:SS format.
The current code is as follows:
item[‘sold_at’]=data[‘sold_at’];
I just want to change this to use the date function to get the date to DD/MM/YY HH:MM format.
How can I do this?
We should use in-built toISOString function to covert it to ISO date format and remove not required data using string manipulation.
let datenow = new Date();
console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"
function generateDatabaseDateTime(date) {
return date.toISOString().replace("T"," ").substring(0, 19);
}
Ideally solution should be to use momentjs or dayjs library.
Adding this answer as well that RobG suggested.
let datenow = new Date;
console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"
function generateDatabaseDateTime(date) {
const p = new Intl.DateTimeFormat('en', {
year:'numeric',
month:'2-digit',
day:'2-digit',
hour:'2-digit',
minute:'2-digit',
second:'2-digit',
hour12: false,
timeZone:'UTC'
}).formatToParts(date).reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, {});
return `${p.year}-${p.month}-${p.day} ${p.hour}:${p.minute}:${p.second}`;
}