javascript 使用javascript将日期和时间字符串组合成单个日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16597853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Combine date and time string into single date with javascript
提问by Vegar
I have a datepickerreturning a date string, and a timepickerreturning just a time string.
我有一个日期选择器返回一个日期字符串,一个时间选择器只返回一个时间字符串。
How should I combine those into a single javascript Date?
我应该如何将它们组合成一个 javascript 日期?
I thought I found a solution in Date.js. The examples shows an at( )
-method, but I can't find it in the library...
我以为我在Date.js 中找到了解决方案。示例显示了一个at( )
-method,但我在库中找不到它...
回答by dm03514
You can configure your date picker to return format like YYYY-mm-dd
(or any format that Date.parse
supports) and you could build a string in timepicker like:
您可以将日期选择器配置为返回格式YYYY-mm-dd
(或任何Date.parse
支持的格式),并且您可以在 timepicker 中构建一个字符串,例如:
var dateStringFromDP = '2013-05-16';
$('#timepicker').timepicker().on('changeTime.timepicker', function(e) {
var timeString = e.time.hour + ':' + e.time.minute + ':00';
var dateObj = new Date(datestringFromDP + ' ' + timeString);
});
javascript Date
object takes a string as the constructor param
javascriptDate
对象接受一个字符串作为构造函数参数
回答by Jan.J
回答by David Silva Smith
For plain JavaScript:
对于纯 JavaScript:
combineDateAndTime = function(date, time) {
timeString = time.getHours() + ':' + time.getMinutes() + ':00';
var year = date.getFullYear();
var month = date.getMonth() + 1; // Jan is 0, dec is 11
var day = date.getDate();
var dateString = '' + year + '-' + month + '-' + day;
var combined = new Date(dateString + ' ' + timeString);
return combined;
};
回答by mtpultz
You can concatenate the date and time, and then use moment to get the datetime
您可以连接日期和时间,然后使用 moment 来获取 datetime
const date = '2018-12-24';
const time = '23:59:59';
const dateTime = moment(`${date} ${time}`, 'YYYY-MM-DD HH:mm:ss').format();
回答by boateng
David's example with slight modifications:
大卫的例子略有修改:
function CombineDateAndTime(date, time) {
var timeString = time.getHours() + ':' + time.getMinutes() + ':00';
var ampm = time.getHours() >= 12 ? 'PM' : 'AM';
var year = date.getFullYear();
var month = date.getMonth() + 1; // Jan is 0, dec is 11
var day = date.getDate();
var dateString = '' + year + '-' + month + '-' + day;
var datec = dateString + 'T' + timeString;
var combined = new Date(datec);
return combined;
};