js日期、月份:日期加一天等
2024-10-19 04:29:51
// 日期,在原有日期基础上,增加days天数,默认增加1天
function addDate(date, days) {
if (days == undefined || days == '') {
days = 1;
}
var date = new Date(date);
date.setDate(date.getDate() + days);
var month = date.getMonth() + 1;
var day = date.getDate();
return date.getFullYear() + '-' + getFormatDate(month) + '-' + getFormatDate(day);
} // 日期月份/天的显示,如果是1位数,则在前面加上'0'
function getFormatDate(arg) {
if (arg == undefined || arg == '') {
return '';
} var re = arg + '';
if (re.length < 2) {
re = '0' + re;
} return re;
}
参考:
如题,开始查了查js的使用文档,但没发现可以直接用的函数,于是就想自己写函数来着,这就要涉及到每个月天数的判断,如果是2月份的话,还要涉及到闰年的判断,虽然不复杂但我想js应该不会这么低级,于是查了下资料,终于有了如下重大发现,以在某个日期上加减天数来说,其实只要调用Date对象的setDate()函数就可以了,具体方法如下:
function addDate(date,days){
var d=new Date(date);
d.setDate(d.getDate()+days);
var m=d.getMonth()+1;
return d.getFullYear()+'-'+m+'-'+d.getDate();
}
其中,date参数是要进行加减的日期,days参数是要加减的天数,如果往前算就传入负数,往后算就传入正数,如果是要进行月份的加减,就调用setMonth()和getMonth()就可以了,需要注意的是返回的月份是从0开始计算的,也就是说返回的月份要比实际月份少一个月,因此要相应的加上1。
最新文章
- nginx-nginx.conf脚本
- an excellent capability of C# language and compiler
- 动态作用域与this +apply和call +bind
- jQuery倒计时
- AFNetworking 提示";The resource could not be loaded because the App Transport Security policy requires the use of a secure connection"; 解决办法
- plsql developer 导出导入存储过程和函数
- hive中grouping sets的使用
- POJ 1006 - Biorhythms (中国剩余定理)
- java静态与非静态区别
- C++注意事项锦集
- iOS开发应用学习笔记
- Entity Framework 使用sql语句分页(查询视图)
- 一个PHP书单 -摘自网络
- UESTC_最少花费 2015 UESTC Training for Dynamic Programming<;Problem D>;
- hdu 4888 Redraw Beautiful Drawings 网络流
- Jmeter 新手
- JVM-类加载器
- 教你如何让数据库支持emoji表情符存储
- github windows配置以及ssh生成 Permission denied (publickey)
- File not found 错误 nginx
热门文章
- Python之路【第十六篇续】Django进阶篇
- SVN Tree Conflict 的分析
- 代码中access 的使用
- cf319.B. Modulo Sum(dp &;&; 鸽巢原理 &;&; 同余模)
- IDEA之google style配置(IDEA)
- 安卓手机当Mac、Win和Linux外置WIFI网卡
- EasyUI中Dialog的使用
- POJ2104 —— K-th number
- Vim编辑器运用的五个技巧
- 通过Unity3d创建二维码(利用zxing2.2)