我有mm-dd-YYYY H:i日期格式,我想在所选日期时间内添加30分钟。
function SetEndDate(start_date){ // start_date = "05-25-2017 05:00"
var duration = '30';
var end_date_tmp = new Date(start_date);
end_date_tmp.setMinutes(duration);
$('#end_date').val(end_date_tmp);
}
它提供无效日期错误。
答案 0 :(得分:2)
由于您的图书馆使用自定义格式(“05-25-2017 05:00”),我建议您尝试fecha library。它通过浏览器正确处理解析/格式化。
function GetEndDate(start_date){ // start_date = "05-25-2017 05:00"
var duration = 30;
var d = fecha.parse(start_date, 'MM-DD-YYYY HH:mm');
d.setMinutes(d.getMinutes() + duration);
return fecha.format(d, 'MM-DD-YYYY HH:mm');;
}
console.log(GetEndDate('05-25-2017 05:00'));
//Call it like so:
//$('#end_date').val(GetEndDate(/* Your variable here */));
<script src="https://cdnjs.cloudflare.com/ajax/libs/fecha/2.3.1/fecha.min.js"></script>
答案 1 :(得分:1)
试试这样:
var newDateObj = new Date();
newDateObj.setTime(oldDateObj.getTime() + (30 * 60 * 1000));
像这样:
function SetEndDate(start_date)
{ // start_date = "05-25-2017 05:00"
var end_date_tmp = new Date(start_date);
end_date_tmp.setTime(start_date.getTime() + (30 * 60 * 1000));
}
答案 2 :(得分:1)
function SetEndDate(start_date){ // start_date = "05-25-2017 05:00" (mm-dd-yyyy) format
var duration = '30';
var my_date_format = function(start_date){
var d = new Date(Date.parse(start_date.replace(/-/g, "/")));
var month = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
var date = d.getFullYear() + "-" + month[d.getMonth()] + "-" + d.getDate();
var time = d.getHours()+":"+d.getMinutes();
var date_time = date + " " + time;
return (date_time);
};
var date_time = my_date_format(start_date);
d2 = new Date ( date_time );
d2.setTime(d2.getTime() + (duration * 60 * 1000));
var date_new = new Date(d2);
yr = date_new.getFullYear();
month = date_new.getMonth() < 10 ? '0' + (date_new.getMonth() + 1) : (date_new.getMonth() + 1);
day = date_new.getDate() < 10 ? '0' + date_new.getDate() : date_new.getDate();
minutes = date_new.getMinutes() < 10 ? '0' + date_new.getMinutes() : date_new.getMinutes();
hours = date_new.getHours() < 10 ? '0' + date_new.getHours() : date_new.getHours();
time = hours + ":" + minutes;
newDate = month + '-' + day + '-' + yr + ' ' + time;
$('#end_date').val(newDate); // you can get new date in "newDate" variable
}