首页 > web前端 > js教程 > 正文

JS日期相加減函數整理

巴扎黑
发布: 2016-11-25 11:07:50
原创
1364人浏览过

// 增加天 
function adddays(date,value) 

date.setdate(date.getdate()+value); 

// 增加月 
function addmonths(date,value) 

date.setmonth(date.getmonth()+value); 

// 增加年 
function addyears(date,value) 

date.setfullyear(date.getfullyear()+value); 

// 是否为今天 
function istoday(date) 

return isdateequals(date,new date()); 

// 是否为当月 
function isthismonth(date) 

return ismonthequals(date,new date()); 

// 两个日期的年是否相等 
function ismonthequals(date1,date2) 

return date1.getmonth()==date2.getmonth()&&date1.getfullyear()==date2.getfullyear(); 

// 判断日期是否相等 
function isdateequals(date1,date2) 

return date1.getdate()==date2.getdate()&&ismonthequals(date1,date2); 

// 返回某个日期对应的月份的天数 
function getmonthdaycount(date) 

switch(date.getmonth()+1) 

case 1:case 3:case 5:case 7:case 8:case 10:case 12: 
return 31; 
case 4:case 6:case 9:case 11: 
return 30; 

//feb: 
date=new date(date); 
var lastd=28; 
date.setdate(29); 
while(date.getmonth()==1) 

lastd++; 
adddays(date,1); 

return lastd; 

// 返回两位数的年份 
function getharfyear(date) 

var v=date.getyear(); 
if(v>9)return v.tostring(); 
return "0"+v; 

// 返回月份(修正为两位数) 
function getfullmonth(date) 

var v=date.getmonth()+1; 
if(v>9)return v.tostring(); 
return "0"+v; 

// 返回日 (修正为两位数) 
function getfulldate(date) 

var v=date.getdate(); 
if(v>9)return v.tostring(); 
return "0"+v; 

// 替换字符串 
function replace(str,from,to) 

return str.split(from).join(to); 

// 格式化日期的表示 
function formatdate(date,str) 

str=replace(str,"yyyy",date.getfullyear()); 
str=replace(str,"mm",getfullmonth(date)); 
str=replace(str,"dd",getfulldate(date)); 
str=replace(str,"yy",getharfyear(date)); 
str=replace(str,"m",date.getmonth()+1); 
str=replace(str,"d",date.getdate()); 
return str; 

// 统一日期格式 
function convertdate(str) 

str=(str+"").replace(/^\s*/g,"").replace(/\s*$/g,""); // 去除前后的空白 
var d; 
if(/^[0-9]{8}$/.test(str)) // 20040226 -> 2004-02-26 

d=new date(new number(str.substr(0,4)),new number(str.substr(4,2))-1,new number(str.substr(6,2))); 
if(d.gettime())return d; 

d=new date(str); 
if(d.gettime())return d; 
d=new date(replace(str,"-","/")); 
if(d.gettime())return d; 
return null; 
}  
js时间差函数 

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号