您的位置:首页 > Web前端 > JavaScript

javascript实用Date工具

2016-07-04 16:02 453 查看
作者最近需要在网页前端进行一些日期相关的计算,发现Date对象提供的方法,使用起来不是那么的方便,于是自己进行了简单的扩展。date转字符串部分的代码是作者直接从网上搜来的我修改了一点点,感谢原作者的分享,其他部分都是原创,分享给大家,欢迎朋友们指正。20160830重新写了getDateFromformatString函数,现在知道策略模式了。感谢我自己。。。。
上代码:

/* 根据传入的格式获取日期的String
对Date的扩展,将 Date 转化为指定格式的String
月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
例子:
(new Date()).Format("YYYY-MM-DD hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
(new Date()).Format("YYYY-M-D h:m:s.S")      ==> 2006-7-2 8:9:4.18 */
Date.prototype.format = function(fmt)
{ //author: meizz
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+)/gi.test(fmt))
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o)
if(new RegExp("("+ k +")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
return fmt;
};

/**
从字符串获取时间对象,请使用Y代表年,M代表月,D代表日,h代表小时,m代表分钟,s代表秒,S代表毫秒(0~999),
每种符号连续出现,不能分隔出现。
**/
function getDateFromformatString(dateString,fmt)
{ //author: yinzhida
var year=1970,month=0,day=1,hour=0,minute=0,second=0,milliseconds=0;
var dateTime={
"Y+":1970,
"M+":0,
"D+":1,
"h+":0,
"m+":0,
"s+":0,
"S+":0,
}
for(key in dateTime){
if(new RegExp("("+key+")").test(fmt)){
dateTime[key] = Number(dateString.substr(new RegExp("("+key+")").exec(fmt).index,
new RegExp("("+key+")").exec(fmt)[0].length));
}
}
var date=new Date(dateTime["Y+"],dateTime["M+"]-1,dateTime["D+"],dateTime["h+"],dateTime["m+"],dateTime["s+"]);
date.setMilliseconds(Number(dateTime["S+"]));
return date;
};

/* 对Date的扩展,减去一个毫秒数的时间 */
Date.prototype.minus = function(milliseconds){
var dateSeconds = this.getTime();
var dateNewSeconds = dateSeconds-milliseconds;
var minusDate = new Date();
minusDate.setTime(dateNewSeconds);
return minusDate;
};

/* 对Date的扩展,加上一个毫秒数的时间 */
Date.prototype.plus = function(milliseconds){
var dateSeconds = this.getTime();
var dateNewSeconds = dateSeconds+milliseconds;
var plusDate = new Date();
plusDate.setTime(dateNewSeconds);
return plusDate;
};

/* 对Date的扩展,获得两个时间的差值,毫秒计算
如果传入的参数(anotherDate)比主体时间更近(更晚发生)那么结果为负数,否则结果为正数*/
Date.prototype.minusDate = function(anotherDate){
var dateSeconds = this.getTime();
var anotherSeconds = anotherDate.getTime();
var howLongTime=dateSeconds-anotherSeconds;
return howLongTime;
};

Date.prototype.isBefore=function(anotherDate){
var dateSeconds = this.getTime();
var anotherSeconds = anotherDate.getTime();
return dateSeconds<anotherSeconds;
};

Date.prototype.isAfter=function(anotherDate){
var dateSeconds = this.getTime();
var anotherSeconds = anotherDate.getTime();
return dateSeconds>anotherSeconds;
};

/**
* 两个date对象之间相差的时间间隔,用string表达:**天**小时**分钟**秒;
* @param anotherDate
* @returns {String}
*/
Date.prototype.minusDateToString = function(anotherDate){
var dateSeconds = this.getTime();
var anotherSeconds = anotherDate.getTime();
var howLongTime=dateSeconds-anotherSeconds;
howLongTime = Math.abs(howLongTime);
var isAllZero = 0;
var timeString="";
var dayNum = Math.floor(howLongTime/(3600000*24));
var dayDid = howLongTime%(3600000*24);
if(dayNum>0){
timeString+=dayNum+"天";
isAllZero+=dayNum;
}
var hourNum = Math.floor(dayDid/3600000);
var hourDid = dayDid%3600000;
if(hourNum>0||(hourNum==0&&isAllZero!=0)){
timeString+=hourNum+"小时";
isAllZero+=hourNum;
}
var minNum = Math.floor(hourDid/60000);
var minDid = hourDid%60000;
if(minNum>0||(minNum==0&&isAllZero!=0)){
timeString+=minNum+"分钟";
isAllZero+=minNum;
}
var secondNum = Math.round(minDid/1000);
if(secondNum>0||(secondNum==0&&isAllZero!=0)){
timeString+=secondNum+"秒";
isAllZero+=secondNum;
}
return timeString;
};
// var d=new Date();
// console.log(d.format("yyyy-MM-dd hh:mm:ss"));
// console.log(d.minus(1000*60*30).format("yyyy-MM-dd hh:mm:ss"));
// console.log(d.plus(1000*60*30).format("yyyy-MM-dd hh:mm:ss"));
// console.log(d.minusDate(d.plus(1000*60*30)));
// console.log(d.minusDate(d.minus(1000*60*30)));
var d=getDateFromformatString("2016-06-12 14:02:05.336","YYYY-MM-DD hh:mm:ss.S");
console.log(d.format("YYYY-MM-DD hh:mm:ss.S"));
var g=getDateFromformatString("2016/06/12-12:12:12","YYYY/MM/DD-hh:mm:ss");
console.log(g.format("YYYY-MM-DD hh:mm:ss.S"));
// var d=new Date();
// var g=d.plus(1000*60*30);
// console.log(d.isBefore(g));
// console.log(d.isAfter(g));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  date js format