how to add 30 minutes in Date Time in Jquery?
我有mm-dd-YYYY H:i日期格式,我想在选定的日期时间添加30分钟。
1 2 3 4 5 6 7 | 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); } |
它给出了无效的日期错误。
由于您的图书馆使用自定义格式("05-25-2017 05:00"),我建议您尝试使用fecha库。 它通过浏览器正确处理解析/格式化。
1 2 3 4 5 6 7 8 9 10 11 | 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 */)); |
1 | <script src="https://cdnjs.cloudflare.com/ajax/libs/fecha/2.3.1/fecha.min.js"> |
试试这样:
1 2 | var newDateObj = new Date(); newDateObj.setTime(oldDateObj.getTime() + (30 * 60 * 1000)); |
像这样:
1 2 3 4 5 | 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)); } |
请参阅此链接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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 } |