views:

568

answers:

2

Hi, i need to concatenate a date value and a time value to make one value representing a datetime in javascript.

thanks, daniel

A: 

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.

stefpet
sorry for the insufficient info. I am using a datapicker to allow the user to pick a date that is represented as: exp: 1/1/2009. The time value is simply a textbox that allows the user to enter a time in this format: hh:mm.
danielea
@danielea: `1/1/2009` is ambiguous, is it `month-day-year`, or `day-month-year`?
CMS
it is (month-day-year). Additionally, the end results needs to be in the following format: (month-day-year hh:mm:ss) and then it needs to be URLEncoded
danielea
A: 

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;
jonthornton
1. The javascript date object will do some funny things when parsing. For example, 11:70 will be interpreted as 12:10.2. The resulting datetime will be in the browser's timezone3. If the input is invalid, isNaN(datetime.getTime()) == true
Ed
True on all points.However, the OP made no mention of validating the inputs, so the assumption is that the date and time values collected are valid string representations of dates and times.
jonthornton