[英]Concatenate a date and time value
i need to concatenate a date value and a time value to make one value representing a datetime in javascript. 我需要连接日期值和时间值,以便在javascript中创建一个表示日期时间的值。
thanks, daniel 谢谢,丹尼尔
I could not make the accepted answer work so used moment.js 我无法让接受的答案工作,所以使用了moment.js
date = moment(selected_date + ' ' + selected_time, "YYYY-MM-DD HH:mm");
date._i "11-06-2014 13:30"
Assuming "date" is the date string and "time" is the time string: 假设“date”是日期字符串,“time”是时间字符串:
// create Date object from valid string inputs
var datetime = new Date(date+' '+time);
// format the output
var month = datetime.getMonth()+1;
var day = datetime.getDate();
var year = datetime.getFullYear();
var hour = this.getHours();
if (hour < 10)
hour = "0"+hour;
var min = this.getMinutes();
if (min < 10)
min = "0"+min;
var sec = this.getSeconds();
if (sec < 10)
sec = "0"+sec;
// put it all togeter
var dateTimeString = month+'/'+day+'/'+year+' '+hour+':'+min+':'+sec;
Working with strings is fun and all, but let's suppose you have two datetimes and don't like relying on strings. 使用字符串很有趣,但是假设你有两个日期时间并且不喜欢依赖字符串。
function combineDateWithTime(d, t)
{
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
t.getHours(),
t.getMinutes(),
t.getSeconds(),
t.getMilliseconds()
);
}
Test: 测试:
var taxDay = new Date(2016, 3, 15); // months are 0-indexed but years and dates aren't.
var clockout = new Date(0001, 0, 1, 17);
var timeToDoTaxes = combineDateWithTime(taxDay, clockout);
// yields: Fri Apr 15 2016 17:00:00 GMT-0700 (Pacific Daylight Time)
Depending on the type of the original date and time value there are some different ways to approach this. 根据原始日期和时间值的类型,有一些不同的方法可以解决这个问题。
A Date object (which has both date and time) may be created in a number of ways. 可以以多种方式创建Date对象(具有日期和时间)。
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
If the original date and time also is objects of type Date, you may use getHours(), getMinutes(), and so on to extract the desired values. 如果原始日期和时间也是Date类型的对象,则可以使用getHours(),getMinutes()等来提取所需的值。
For more information, see Mozilla Developer Center for the Date object. 有关更多信息,请参阅Date对象的Mozilla开发人员中心。
If you provide more detailed information in your question I may edit the answer to be more specific. 如果您在问题中提供更详细的信息,我可以编辑答案以使其更具体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.