Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine date and time string into single date with javascript

I have a datepicker returning a date string, and a timepicker returning just a time string.

How should I combine those into a single javascript Date?

I thought I found a solution in Date.js. The examples shows an at( )-method, but I can't find it in the library...

like image 412
Vegar Avatar asked May 16 '13 21:05

Vegar


People also ask

How do I combine a date and a timestamp?

To combine date and time column into a timestamp, you can use cast() function with concat(). select cast(concat(yourDateColumnName, ' ', yourTimeColumnName) as datetime) as anyVariableName from yourTableName; In the above concept, you will use cast() when your date and time is in string format.

How do you convert a string to a date in JavaScript?

Use the Date() constructor to convert a string to a Date object, e.g. const date = new Date('2022-09-24') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.

Can JavaScript handle date and time?

The date and time is broken up and printed in a way that we can understand as humans. JavaScript, however, understands the date based on a timestamp derived from Unix time, which is a value consisting of the number of milliseconds that have passed since midnight on January 1st, 1970.


2 Answers

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:

 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

like image 128
dm03514 Avatar answered Sep 20 '22 12:09

dm03514


Combine date and time to string like this:

1997-07-16T19:20:15 

Then you can parse it like this:

Date.parse('1997-07-16T19:20:15'); 

You could also use moment.js or something similar.

like image 30
Jan.J Avatar answered Sep 17 '22 12:09

Jan.J