Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI datepicker to epoch

What is the best way to get a datepicker date in the following format yyyy-dd-mm (yy-dd-mm in datepicker settings) and convert it into epoch time with Javascript?

I was trying to do it like this:

var aDate = $("#date").val().split('-');
var epoch = new Date(aDate[0] + "," + aDate[1] + "," + aDate[2]).getTime() / 1000;

And a console.log(epoch) comes back as NaN.

But if I declare epoch as new Date(2011,10,30).getTime() / 1000; then there is no problems. I am guessing the problem is that I am passing in a string, but I have no clue how to solve it as I am new to Javascript.

Edit: I know about the altDate and altFormat settings in datepicker. But I want to know how to do it without using those setting. Because I will have to do what I am describing above for date + time later.

like image 810
halliewuud Avatar asked Aug 20 '11 00:08

halliewuud


3 Answers

Try changing your date constructor to this:

var epoch = new Date(aDate[0], aDate[1] - 1, aDate[2]).getTime() / 1000;

We've removed the string concatenation, so it should read the date correctly. Month is represented as aDate[1] - 1 because month numbers in JavaScript are zero based (January = 0, December = 11), so 1 needs to be subtracted from the month number.

You can find a working example here: http://jsfiddle.net/Qpg24/67/

like image 64
Karl Nicoll Avatar answered Nov 20 '22 06:11

Karl Nicoll


jQuery UI datepicker's altDate and altFormat parameters will do this for you automatically.

Check out the "Populate alternate field" example in the examples.

like image 26
Pekka Avatar answered Nov 20 '22 05:11

Pekka


jQuery UI datepicker has a 'getDate' method that returns the date as a string:

Sun Apr 28 2013 13:30:00 GMT+1000 (EST)

You can use the 'getTime' method of a Date object to convert this string into milliseconds since the epoch. Using your example code, this would look like:

var epoch = new Date( $("#date").datepicker( "getDate" ) ).getTime();

This works for jQuery datetimepicker as well (http://trentrichardson.com/examples/timepicker/)

like image 1
Ben Avatar answered Nov 20 '22 05:11

Ben