开发者

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 kno开发者_开发技巧w how to do it without using those setting. Because I will have to do what I am describing above for date + time later.


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/


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

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


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/)


dateFormat: '@',

$("#input").datepicker({
    dateFormat: '@',
    maxDate : 0,
    onSelect: function() {
        var input = $(this).datepicker('getDate');
        console.log('%c input = ' + input, "color: green;");
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜