How to I modify the below function to output date in the desired format, please?
Sending date to be formatted:
Original format: 2015-10-27 21:41:22
var d = new Date(globalStore.data[i].DateReg);
var e = formatDate(d);
Date function:
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'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;//to show time
return date.getDate() + "/" + date.getMonth() + "/" + date.getFullYear() + " ";
}
Desired format:
14 Nov 2015
Date formatting is very tedious, why not find an easy way.. Use moment.js
pretty simple,
var date = moment().format('DD MMM YYYY')
If you want 14 Nov 2015
var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
var date = new Date();
var yourDateformat = date.getDate() + " " + monthNames[date.getMonth()] + " " + date.getFullYear();
I suggest to use library moment.js
var d = moment(globalStore.data[i].DateReg, 'YYYY-MM-DD HH:mm:ss'); // Convert raw date type string to type Datetime
moment(d).format('DD MMM YYYY'); // 27 Nov 2015
OR
function formateDate(strDate) {
return moment(globalStore.data[i].DateReg, 'YYYY-MM-DD HH:mm:ss').format('DD MMM YYYY');
}
Also i suggest momment.js
lib, but if you can't use additional libraries you can achieve that using an array of short month names :
var shodtMonthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var d = new Date("2015-10-27 21:41:22"); var day = d.getDate(); var month = shodtMonthNames[d.getMonth()]; var year = d.getFullYear(); console.log( day + " " + month + " " + year );
Hope this helps.
It's a bit lame solution, but I don't think defining a new array to keep month names is necessary. You can use the ones you already have.
var date = new Date().toDateString().split(' ');
// 'Sat Nov 28 2015'
var result = date[2] +' '+ date[1] +' '+ date[3];
// '28 Nov 2015'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.