有什么好的方法可以将字符串转化为日期?

Henry712 2010-12-07 10:33:55
如字符串“2010-12-07”,直接用Date()对象无法转换,需要特定格式。目前我是自己将字符串拆成年、月、日的数值,再用Date()转换。有什么好的办法能让Date()直接识别“YYYY-MM-DD”吗?
...全文
60 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
蓝海 2010-12-07
  • 打赏
  • 举报
回复
学习 1、2、3 楼,真牛啊。。。
浴火_凤凰 2010-12-07
  • 打赏
  • 举报
回复
自己吧字符串解析一下不就得了
root_lee 2010-12-07
  • 打赏
  • 举报
回复
自己扩展吧。
<script type="text/javascript">
Date.prototype.fromString = function(strDate,sep){
var arr = strDate.split(sep);
this.setFullYear(arr[0]||"",arr[1]||"",arr[2]||"");
}
var date = new Date();
date.fromString("2010-11-7","-");
alert(date.getDate());
</script>
hch126163 2010-12-07
  • 打赏
  • 举报
回复
Date.prototype.format = function(format)
{
var o ={
'M+' : this.getMonth()+1, //month
'd+' : this.getDate(), //day
'h+' : this.getHours(), //hour
's+' : this.getSeconds(), //second
'm+' : this.getMinutes(), //minute
'q+' : Math.floor((this.getMonth()+3)/3), //quarter
'S' : this.getMilliseconds() //millisecond
};
if(/(y+)/.test(format)){format=format.replace(RegExp.$1,(this.getFullYear()+'').substr(4 - RegExp.$1.length));}
for(var k in o){
if(new RegExp('('+ k +')').test(format)){format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ('00'+ o[k]).substr((''+ o[k]).length));}}
return format;
};

new Date().format('yyyy年MM月dd日hh时mm分');
Mr-Jee 2010-12-07
  • 打赏
  • 举报
回复
var t = new Date(d.split("-").join(","));

87,904

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧