js中将一串字符串转换为date类型,主要是先过滤字符,然后分割开,如下代码实例:
function parseToDate(strTime){
var arr=strTime.split(" ")
if(arr.length>=2)
{
var arr1=arr[0].split("-")
var arr2=arr[1].split(":")
}
else
return null
if(arr1.length>=3 && arr2.length>=3)
{
var b=new Date(arr1[0],arr1[1],arr1[2],arr2[0],arr2[1],arr2[2])//将字符串转换为date类型
return b
}
else
return null
}
var date = 'Mon Sep 15 21:21:29 +0800 2014'var result = date.split(' ')
var year = result.pop()
result.splice(3, 0, year)
date = result.join(' ')
console.log(date) // 输出:Mon Sep 15 2014 21:21:29 +0800
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>