moikey moikey - 7 months ago 91
Javascript Question

JQuery datetime to milliseconds

I have a web application where I wish to send information to a database.

I have a datepicker, which lets the user select a date and formats the date as

. In addition to this, the users must also select a time using a
which formats the time as
. This gets concatenated into a
string as

I need to convert this into milliseconds for the datetime to be accepted as the correct format on the database (locale format of

I have a tried a host of solutions found here and elsewhere to try and convert into milliseconds. Whenever I try to concat then convert I usually get a NaN error or "invalid Date" and I cannot simply add the converted milliseconds.

Is there any way of doing this in jQuery or JavaScript?


I managed to figure this one out myself. Thanks to those who answered. Its not an ideal solution, but it works.

var d = $("#date").val();
var dateParts = new Date((Number(d.split("-")[0])), (Number(d.split("-")[1]) - 1), (Number(d.split("-")[2])));
var dateis = dateParts.getTime();

var timeEnd = $("#endtime").val();
var time1 = ((Number(timeEnd.split(':')[0]) * 60 + Number(timeEnd.split(':')[1]) * 60) * 60) * 1000;

var timeStart = $("#starttime").val();
var time2 = ((Number(timeStart.split(':')[0]) * 60 + Number(timeStart.split(':')[1]) * 60) * 60) * 1000;

var dateTimeEnd = dateis + time1;
var dateTimeStart = dateis + time2;

What this basically does, is take a date from a datepicker, and a start and an endtime from a timepicker. The ajax accepts 2 datetimes, one for start, one for end. The above solution basically gets all the values from the input values, and converts it to milliseconds. It's not the best way of doing things but it is a quick fix.