Date formatting:
Note: It needs to be converted to a string when passed in
function nowTime(mytime) { let time = new Date(mytime); // year: let year = time.getFullYear(); // month let month = time.getMonth() + 1; month = month < 10 ? '0' + month : month; // let date = time.getDate(); date = date < 10 ? '0' + date : date; // let hour = time.gethours (); hour = hour < 10 ? '0' + hour : hour; // let minute = time.getminutes (); minute = minute < 10 ? '0' + minute : minute; // let second = time.getseconds (); second = second < 10 ? '0' + second : second; Let timeStr = ` - $${year} years on - ${date} {the month} ${hour} : ${minute} : ${second} `; return timeStr; } console.log(nowTime('Wed Jan 01 2020 20:30:12 GMT+0800 (CST)');Copy the code
Target time countdown:
function getTime() { let time = new Date(); // year: let year = time.getFullYear(); // month let month = time.getMonth() + 1; month = month < 10 ? '0' + month : month; // let date = time.getDate(); date = date < 10 ? '0' + date : date; // let hour = time.gethours (); hour = hour < 10 ? '0' + hour : hour; // let minute = time.getminutes (); minute = minute < 10 ? '0' + minute : minute; // let second = time.getseconds (); second = second < 10 ? '0' + second : second; Let timeStr = ` - $${year} years on - ${date} {the month} ${hour} : ${minute} : ${second} `; return timeStr; } let a = getTime(); // console.log(a); function countDown() { let b = document.getElementById('mydiv'); let futureTime = +new Date('2021-7-31 21:00:00'); let nowTime = +new Date(); let res = futureTime - nowTime; res = res / 1000; // Convert to seconds; let day = parseInt(res / 60 / 60 / 24); let hour = parseInt(res / 60 / 60 % 24); let minate = parseInt(res / 60 % 60); let second = parseInt(res % 60); B.innertext = '${day} days,${hour} hours,${minate} minutes,${second} seconds'; } countDown(); // call the function first to prevent a blank interval of 100ms; setInterval(countDown, 100);Copy the code
Date Formatting 2
Parameter 1: timestamp, parameter 2 date format
function parseTime (time, cFormat) { if (arguments.length === 0) { return null } if ((time + '').length === 10) { time = +time * 1000 } const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}' let date if (typeof time === 'object') { date = time } else { date = new Date(parseInt(time)) } const formatObj = { y: date.getFullYear(), m: date.getMonth() + 1, d: date.getDate(), h: date.getHours(), i: date.getMinutes(), s: date.getSeconds(), a: date.getDay() } const timeStr = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, Key) = > {let value = formatObj [key] if (key = = = 'a') {return [' a ', '2', '3', '4', '5', '6', ', '] [value - 1]} the if (result. The length > 0 && value < 10) + value} {value = '0' return value | | 0}) return timeStr}Copy the code