天天看點

js-格式化目前日期

//第一種方式 new Date()擷取 格式化目前日期 function getNowFormatDate() { var date = new Date(); var seperator1 = "-"; var seperator2 = ":"; var month = date.getMonth() + 1; var strDate = date.getDate(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } if (date.getHours() >= 0 && date.getHours() <= 9) { hours = "0" + date.getHours(); } if (date.getMinutes() >= 0 && date.getMinutes() <= 9) { minutes = "0" + date.getMinutes(); } if (date.getSeconds() >= 0 && date.getSeconds() <= 9) { seconds = "0" + date.getSeconds(); } var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate + " " + hours + seperator2 + minutes+ seperator2 + seconds; return currentdate; }

//第二種方式 正規表達式 格式化日期

function parseDate (s) { // 将字串解析成日期值 友善作比較 var dv , reg = /^\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d$/gi ; if (! reg . test (s)) { window . alert ( " 日期值格式錯誤 !" ); return null ; } else { dv = new Date(Date. parse (s. replace ( /-/g , "/" )));

if ( dv . getFullYear () != eval (s. substring ( 0 , 4 )) || dv . getMonth () + 1 != eval (s. substring ( 5 , 7 )) || dv . getDate () != eval (s. substring ( 8 , 10 ))

|| dv . getHours () != eval (s. substring ( 11 , 13 )) || dv . getMinutes () != eval (s. substring ( 14 , 16 )) || dv . getSeconds () != eval (s. substring ( 17 , 19 )) ) { window . alert ( " 日期值錯誤 !" ); return null ; } } return dv; }

繼續閱讀