Javascript日期时间总结
作者:Alpha时间:2017-09-14 阅读数:2263 +人阅读
JS时间格式化处理
2.1转换为:yyyy-MM-dd HH:mm:ss格式
代码如下:
// 说明:JS时间Date格式化参数// 参数:格式化字符串如:'yyyy-MM-dd HH:mm:ss'// 结果:如2016-06-01 10:09:00Date.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() }; var year = this.getFullYear(); var yearstr = year + ''; yearstr = yearstr.length >= 4 ? yearstr : '0000'.substr(0, 4 - yearstr.length) + yearstr; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (yearstr + "").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; }
2.2如:1993年02月08日 转换后为 08FEB93
代码如下:
// 说明:转换js的Date为:// 参数:JS的的Date// 返回:例如:1993年02月08日 转换后为 08FEB93var parseDateStr = function(d) { var array = d.toDateString().split(' '); var str = array[2]+array[1]+array[3].substr(2,2); return str.toUpperCase() }
3 常见JS的Date的函数
如图所示:
4 两个时间相减
4.1 两个日期相减——秒
代码如下:
// 说明:两个时间相减// 参数:JS的Date类型,或者 string 类型,格式为:yyyy-MM-dd HH:mm:ss// 返回: date1-date2的秒数var substractDate = function(date1, date2){ var type1 = typeof date1; var type2 = typeof date2; if (type1 == 'string') { date1 = new Date(date1); } if (type2 == 'string') { date2 = new Date(date2); } return (date1 - date2) / 1000; }
测试结果,如图所示:
根据数学知识:
1天=24小时
1小时=60分
1分=60秒
来推导出,相差的分钟数,小时,天数
4.2 两个日期相减——月份
两个日期相差的月份,不能简单的以1个月有多少天来计算,因为有的月份有30天,有的有31天。所以是下面这种计算方式。相差的年份的计算可以参考下面这种方式。
代码如下:
var getDiffMonths = function(date1, date2) { if (!date1 instanceof Date){ console.error('param date1 is not Date'); } if (!date2 instanceof Date){ console.error('param date2 is not Date'); } var months1 = date1.getFullYear() * 12 + date1.getMonth(); var months2 = date2.getFullYear() * 12 + date2.getMonth(); return months1 - months2; }
测试结果,如图所示:
4 时间相加
4.1 两个日期相加——天
代码如下:
Date.prototype.addDays = date = Date(+
相加月份,年份,参照上面的代码。
本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:595397166@qq.com