js中字符串怎么转化为日期

字符串格式为str = "2010-08-01";怎么把它转化为日期,并且在day上面加1,谢谢各位!

var str = "2010-08-01";
// 转换日期格式
str = str.replace(/-/g, '/'); // "2010/08/01";
// 创建日期对象
var date = new Date(str);
// 加一天
date.setDate(date.getDate() + 1);

追问

要再格式化为原来str的格式,我这样怎么不行额....
date = date.format("yyyy-MM-dd") ;

追答var str = "2010-08-01";
// 转换日期格式
str = str.replace(/-/g, '/'); // "2010/08/01";
// 创建日期对象
var date = new Date(str);
// 加一天
date.setDate(date.getDate() + 1);
// 没有格式化的功能,只能一个一个取
str = date.getFullYear() + '-'
    // 因为js里month从0开始,所以要加1
    + (parseInt(date.getMonth()) + 1) + '-'
    + date.getDate();

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-08-04
js 把字符串转化为日期参考代码如下:
var s ='2017-04-18 09:16:15';
s = s.replace(/-/g,"/");
var date = new Date(s );

解释说明:
/-/g 是正则表达式
表示将所有短横线-替换为斜杠/
其中g表示全局替换本回答被网友采纳
第2个回答  2013-12-13
function StringToDate(DateStr)
{
var converted = Date.parse('2009/01/05');
alert(converted);
alert(DateStr.substr(0,4)+"/"+DateStr.substr(5,2)+"/"+DateStr.substr(8,2));
var myDate = new Date(converted);
alert(myDate);
alert(myDate.getFullYear()+"/"+ (myDate.getMonth()+1) +"/"+myDate.getDate());
if (isNaN(DateStr))
{
//var delimCahar = DateStr.indexOf('/')!=-1?'/':'-';
DateStr = "2008-08-08";
var arys= DateStr.split('-');
var d = new Date(arys[0], arys[1], arys[2]);
alert(d);
}
//alert(myDate);
return myDate;
}追问

要再格式化为原来str的格式,我这样怎么不行额....
date = date.format("yyyy-MM-dd") ;

追答

什么意思?你是要Date格式化一下?

追问

恩,格式化为str一样的格式

追答

var myDate = new Date();
var dataStr=myDate.getFullYear()+"-"+ (myDate.getMonth()+1) +"-"+myDate.getDate();

第3个回答  2013-12-18

其实碰见这种问题,我们最好封装一个util的函数,以备后来的需要。

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
调用: 
var time1 = new Date().Format("yyyy-MM-dd");
var time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");
var day = time2.getDate()

day =