Javascript 在 HTML DOM 中获取工夫不麻烦,然而想要获取指定格局的工夫却很麻烦,上面的办法能够使 Javascript 像 C# 获取 DateTime 类的工夫那样获取零碎以后的工夫,应用办法如 GetCurrentTime("yyyy/MM/dd HH:mm:ss"):
function GetCurrentTime(_format) { var date = new Date(); if (!_format) { return date.toLocaleString(); } if (/y/i.test(_format)) { _format = _format.replace(/(yyyy)/i, date.getFullYear()); _format = _format.replace(/(yy)/i, (date.getYear() % 100) > 9 ? (date.getYear() % 100).toString() : '0' + (date.getYear() % 100)); } if (/M/.test(_format)) { _format = _format.replace(/(MM)/, date.getMonth() > 8 ? (date.getMonth() + 1).toString() : '0' + (date.getMonth() + 1)); _format = _format.replace(/(M)/, date.getMonth() + 1); } if (/d/i.test(_format)) { _format = _format.replace(/(dd)/i, date.getDate() > 9 ? date.getDate().toString() : '0' + date.getDate()); _format = _format.replace(/(d)/i, date.getDate()); } if (/h/i.test(_format)) { _format = _format.replace(/(hh)/i, date.getHours() > 9 ? date.getHours().toString() : '0' + date.getHours()); _format = _format.replace(/(h)/i, date.getHours()); } if (/m/.test(_format)) { _format = _format.replace(/(mm)/, date.getMinutes() > 9 ? date.getMinutes().toString() : '0' + date.getMinutes()); _format = _format.replace(/(m)/, date.getMinutes()); } if (/s/i.test(_format)) { _format = _format.replace(/(ss)/i, date.getSeconds() > 9 ? date.getSeconds().toString() : '0' + date.getSeconds()); _format = _format.replace(/(s)/i, date.getSeconds()); } if (/f/i.test(_format)) { _format = _format.replace(/(fff)/i, date.getMilliseconds().toString().substr(0, 3)); _format = _format.replace(/(ff)/i, date.getMilliseconds().toString().substr(0, 2)); _format = _format.replace(/(f)/i, date.getMilliseconds().toString().substr(0, 1)); } return _format;}
_format 参数指年月日、时分秒和毫秒格式化字符,别离能够是 yyyy, yy, MM, M, dd, d, hh, h, mm, m, ss, s, fff, ff, f,其中大写 M 代表月份,小写 m 代表分钟,其它字符不辨别大小写,能够和任意其它字符进行格局组合,如 “ yy年M月d日 ”,单写和双写模式相似 .NET Framework 中的区别,如 MM 可能为固定长度的月份 “ 03 ”,而 M 可能为可变长度的月份 “ 3 ”。