简体   繁体   中英

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.

thanks, daniel

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;

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM