JS中String类型转换Date类型 并 计算时间差
2024-10-09 23:22:10
JS中String类型转换Date类型
1、比较常用的方法,但繁琐,参考如下:
主要使用Date的构造方法:Date(int year , int month , int day)
<script>
var str1 = "2009-8-9";
var arr1 = str1.split("-");
var date1 = new Date(arr1[0],parseInt(arr1[1])-1,arr1[2]);
var str2 = "2009-8-4";
var arr2 = str2.split("-");
var date2 = new Date(arr2[0],parseInt(arr2[1])-1,arr2[2]);
alert(date1>date2);//true
</script>
2、相对简便的方法,参考如下:
var str = "2005-12-15";
var d = new Date(str.replace(/-/g, "/"));
Example:
<script>
var s = "2010-09-11";
var s1 = "2010-09-12";
var d = new Date(s.replace(/-/g,"/"));
var d1 = new Date(s1.replace(/-/g,"/"));
var m = (d1.getTime()-d.getTime())/(1000*60*60);
alert(m); //24
</script>
JS 时间相减得出天数
// 给日期类对象添加日期差方法,返回日期与diff参数日期的时间差,单位为天
Date.prototype.diff = function(date){
return (this.getTime() - date.getTime())/(24 * 60 * 60 * 1000);
}
// 构造两个日期,分别是系统时间和2013/04/08 12:43:45
var now = new Date();
var date = new Date('2013/04/08 12:43:45');
// 调用日期差方法,求得参数日期与系统时间相差的天数
var diff = now.diff(date);
// 打印日期差
alert(diff);
最新文章
- (42) Aeroo 模板实战
- 互斥锁(Mutex)
- Struts2 用 s:if test 判断属性和字符串相等时 注意双引号和单引号的使用
- hadoop的wordcount例子运行
- 库函数strlen源码重现及注意问题
- HTML不常用元素:optgroup
- Fedora24 升级到25
- FPGA学习:VHDL设计灵活性&不同设计思路比较
- GCD hdu2588
- JavaScript正则表达式模式匹配(3)——贪婪模式和惰性模式
- react组件中刷新组件小技巧
- vue项目关闭eslint检查
- vim 批量替换使用说明
- python 模块之-pickle
- Edge 浏览器 调用
- MISL Learning
- 国家code和区号计算
- Template、ItemsPanel、ItemContainerStyle、ItemTemplate (部分内容有待验证)
- Ansible 小手册系列 十五(Blocks 分组)
- 玩转Eclipse — 自动代码规范检查工具Checkstyle