We discuss in this artical how to change date format in javascript.
For get month,date,year,hour,min,sec from the given date in javascript.
Use this function for get date format in javascript.
dt= current d
function formatDate(dt) {
var month = (dt.getMonth()+1).toString().padStart(2, '0');
var date= dt.getDate().toString().padStart(2, '0');
var year= dt.getFullYear().toString().padStart(4, '0') ;
var hour= dt.getHours().toString().padStart(2, '0');
var min= dt.getMinutes().toString().padStart(2, '0');
var sec= dt.getSeconds().toString().padStart(2, '0');
return year+'-'+month+'-'+date+' '+formatAMPM(dt);
//console.log(year+'-'+month+'-'+date+' '+formatAMPM(dt));
}
formatAMPM () function for get time in Am/PM.
For date convert in to human readable time format in javascript.
function formatAMPM(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;
return strTime;
}
For get month,date,year,hour,min,sec from the given date in javascript.
Use this function for get date format in javascript.
dt= current d
ate.
function formatDate(dt) {
var month = (dt.getMonth()+1).toString().padStart(2, '0');
var date= dt.getDate().toString().padStart(2, '0');
var year= dt.getFullYear().toString().padStart(4, '0') ;
var hour= dt.getHours().toString().padStart(2, '0');
var min= dt.getMinutes().toString().padStart(2, '0');
var sec= dt.getSeconds().toString().padStart(2, '0');
return year+'-'+month+'-'+date+' '+formatAMPM(dt);
//console.log(year+'-'+month+'-'+date+' '+formatAMPM(dt));
}
formatAMPM () function for get time in Am/PM.
For date convert in to human readable time format in javascript.
function formatAMPM(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;
return strTime;
}
No comments:
Post a Comment