网上现有的字符串 转 Date, 都是指定的几个格式
我实现了一个任意格式的, 只需要传入格式字符串就行了, 这个你在网上找不到
网上现有的Date.prototype.format也有一个小bug, 我也去掉了
下面的代码去除了网上 Date.prototype.format 的bug, 毫秒对应三位
(网上的 SSS 只有第一个S对应毫秒, 后面两个无效, 被映射成SS, 这个绝对不是我们想要的)
为此改了if 语句 :
Date.prototype.format = function (format) {
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S+": this.getMilliseconds()
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
var replaceWith;
if (RegExp.$1.length == 1)
replaceWith = o[k];
else if (k == "S+")
replaceWith = ("000" + o[k]).substr(("" + o[k]).length);
else
replaceWith = ("00" + o[k]).substr(("" + o[k]).length);
format = format.replace(RegExp.$1, replaceWith);
}
}
return format;
}
然后提供我写的 strToDate
// inputDateStr 必须与 inputFormat 一一对应且等长
function strToDate(inputDateStr, inputFormat) {
var cur = new Date();
var obj = {
y: cur.getYear(),
M: 1,
d: 1,
h: 0,
m: 0,
s: 0,
S: 0
};
// 预处理, 删除format 中 yMdhmsS 之外的字符, 同时删除str对应的字符
var str = "";
var format = "";
for (var i=0; i<inputFormat.length; ++i) {
if ("yMdhmsS".indexOf(inputFormat.charAt(i)) >= 0) {
str += inputDateStr[i];
format += inputFormat[i];
}
}
var startIdx=0, endIdx;
while (startIdx < format.length) {
var startChar = format.charAt(startIdx);
endIdx = startIdx+1;
while (endIdx < format.length && format.charAt(endIdx) == startChar)
++endIdx;
obj[startChar] = parseInt(str.substring(startIdx, endIdx));
startIdx = endIdx;
}
return new Date(obj.y, obj.M - 1, obj.d, obj.h, obj.m, obj.s, obj.S);
}
测试代码
alert(strToDate("2015-01-02 <26> 03:04:05", "yyyy-dd-MM <SS> hh:mm:ss").format("yyyy-MM-dd hh:mm:ss SSS"));
可以看到我的代码风格是纯C的, 纯后端人员