在web开发中,常常会碰到时间转换成指定的字符串形式,如果是后台,没什么问题(有现成的系统方法,如C#:DateTime.ToString("yyyy-MM-dd")),但在前端得自己写一个转换的方法(我好像没有看到过现成的js包,不知道是不是自己知识面太窄了),近来整理一些东西,顺便把这个贴出来(仿后台的转换方式,但有种情况没有兼容:DateTime.ToString("yyyy-MMM-dd"),此时月份会转换成中文,我做的项目中没有用到转换成中文日期的情况,所以暂时没写;其次,目前支持json类型的时间和js内置的时间类型),各位勿喷
function DateToString(dateFormat, currentDate) {
if (null == currentDate) {
throw new Error("the value of date is required");
}
//json类型的时间
var date_pattern = /^\/Date\(\d{13}\)\/$/;
if (date_pattern.test(currentDate)) {
currentDate = new Date(parseInt(currentDate.replace("/Date(", "").replace(")/", "")));
}
else if (!(currentDate instanceof Date)) {
throw new Error("the data type is invalid");
}
var year = currentDate.getFullYear();
var month = currentDate.getMonth() + 1;
var day = currentDate.getDate();
var hour = currentDate.getHours();
var minute = currentDate.getMinutes();
var second = currentDate.getSeconds();
var millisecond = currentDate.getMilliseconds();
var match_result;
var json = [
{ "p": "y+", "v": year, "c": "y" },
{ "p": "M+", "v": month, "c": "M" },
{ "p": "d+", "v": day, "c": "d" },
{ "p": "h+", "v": hour > 12 ? hour - 12 : hour, "c": "h" },
{ "p": "H+", "v": hour, "c": "H" },
{ "p": "m+", "v": minute, "c": "m" },
{ "p": "s+", "v": second, "c": "s" },
{ "p": "f+", "v": millisecond, "c": "f" }
];
var m = eval(json);
for (var i = 0; i < m.length; i++) {
var _reg = new RegExp(m[i].p, "g");
while ((match_result = _reg.exec(dateFormat)) != null) {
match_result = match_result[0];
var value = m[i].v;
switch (m[i].c) {
case 'y':
if (match_result.length <= 2) {
dateFormat = dateFormat.replace(match_result, value.toString().substr(2, 2));
}
else {
dateFormat = dateFormat.replace(match_result, value);
}
break;
case 'M':
case 'd':
case 'h':
case 'H':
case 'm':
case 's':
if (match_result.length <= 1) {
dateFormat = dateFormat.replace(match_result, value);
}
else {
dateFormat = dateFormat.replace(match_result, value < 10 ? "0" + value : value);
}
break;
case 'f':
switch (match_result.length) {
case 1:
dateFormat = dateFormat.replace(match_result, value.toString().substr(0, 1));
break;
case 2:
dateFormat = dateFormat.replace(match_result, value.toString().substr(0, 2));
break;
default:
dateFormat = dateFormat.replace(match_result, value);
break;
}
break;
}
}
}
return dateFormat;
}
调用方式:DateToString("yyyyy年MM月dd日", val);

被折叠的 条评论
为什么被折叠?



