jQuery,添加日期

时间:2014-07-14 12:33:29

标签: javascript jquery

在我的Ruby on Rails应用程序中,我有一个用户可以设置日期的字段。该字段值具有以下格式:

$('#search_form_handover_date').val()
#returns
"15-07-2014 09:00"

现在,我如何能够将此日期添加到3天,以便: “18-07-2014 09:00”

2 个答案:

答案 0 :(得分:1)

如果您的日期字符串始终保持相同的格式,请尝试以下内容,

var date = "15-07-2014 09:00";
var dateParts = (date.split(" ")[0]).split("-");
var timeParts = (date.split(" ")[1]).split(":");
var dateObj = new Date(dateParts[2],dateParts[1]-1,dateParts[0],timeParts[0],timeParts[1]);
dateObj.setDate(dateObj.getDate()+3);
console.log(dateObj)

//If you don't use any library like Jquery datepicker, you have to use basic js operation to format the date (but not recommend)   

console.log(formateDate(dateObj))

function formateDate(DateObj)
{
return addLeadingZeros(dateObj.getDate())+"-"+addLeadingZeros(dateObj.getMonth()+1)+"-"+dateObj.getFullYear()+" "+addLeadingZeros(dateObj.getHours())+":"+addLeadingZeros(dateObj.getMinutes());

}

function addLeadingZeros(intArg)
{
    return ('0' + intArg).slice(-2)
}

答案 1 :(得分:1)

我是moment.js的忠实粉丝,如果你不介意使用第三方JS lib,你就可以...... [/ p>

// As the format you gave is non standard, you need to tell moment what it's getting
var myTime = moment("15-07-2014 09:00", "DD-MM-YYYY HH:mm");

console.log(myTime.format('DD-MM-YYYY HH:mm'));

var newTime = moment(myTime).add('3', 'days');

console.log(newTime.format('DD-MM-YYYY HH:mm'));