开发者

Concatenate a date and time value

i need to concatenate a date value a开发者_运维百科nd a time value to make one value representing a datetime in javascript.

thanks, daniel


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)


I could not make the accepted answer work so used 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:

// 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;


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.

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.

For more information, see Mozilla Developer Center for the Date object.

If you provide more detailed information in your question I may edit the answer to be more specific.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜