2 Ocak 2020

Javascript DateTime To Formatted String

function dateToFormat(date, template) { var t = template; var day = date.getDate(); if (t.indexOf('dd') > -1) { if (day < 10) day = `0${day}`; t = t.replace('dd', day); } else t = t.replace('d', day); var month = date.getMonth() + 1; if (t.indexOf('MM') > -1) { if (month < 10) month = `0${month}`; t = t.replace('MM', month); } else t = t.replace('M', month); var year = date.getFullYear(); if (t.indexOf('yyyy') > -1) t = t.replace('yyyy', year); else if (t.indexOf('yyy') > -1) t = t.replace('yyy', `${year}`.substring(1, 4)); else if (t.indexOf('yy') > -1) t = t.replace('yy', `${year}`.substring(2, 4)); else if (t.indexOf('y') > -1) t = t.replace('y', `${year}`.substring(3, 4)); var hour = date.getHours(); if (t.indexOf('HH') > -1) { if (hour < 10) hour = `0${hour}`; t = t.replace('HH', hour); } else t = t.replace('H', hour); var min = date.getMinutes(); if (t.indexOf('mm') > -1) { if (min < 10) min = `0${min}`; t = t.replace('mm', min); } else t = t.replace('m', min); var sec = date.getSeconds(); if (t.indexOf('ss') > -1) { if (sec < 10) sec = `0${sec}`; t = t.replace('ss', sec); } else t = t.replace('s', sec); return t; }