Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing jQuery date to Rails date

I have a rails-generated date, and a jQuery-generated date.

The rails date prints as such: 2002-10-27

and the jQuery date prints as such: Tue Aug 14 2001 00:00:00 GMT-0500 (CDT)

I want to check if the jQuery date is greater or less than the rails date. But no matter the dates, the jQuery date is always interpreted as larger than the rails date.

Why is that, and how can I successfully compare the two dates?

var year = 2001
var month = 9
month --
var day = 14
var date = new Date(year, month, day);
<% @date = Date.today - 18.years %>
if( date > <%= @date %> ) {
  //this code is always executed, no matter what dates I choose
}

UPDATE:

Actually I just figured out the problem is that it only allows dates before 1969. I intended the code to only allow dates over 18 years old. Does anyone know why the difference?

UPDATE 2:

I tested the time output of October 5th, 2000 in my js console and rails consoles, and they give the same first six digits, but the js console adds three zeros.

var year = 2000
var month = 10
month --
var day = 5
var date = new Date(year, month, day);
date.getTime();
=> 970722000000


Date.new(2000,10,5).to_time.to_i
=> 970722000 
like image 831
Jeff Caros Avatar asked Oct 27 '15 23:10

Jeff Caros


4 Answers

So it turns out the issue is that the js console prints times in milliseconds, which is why I was getting 973404000000, versus 973404000 in the rails console.

All I had to do was divide the js time by 1000, and comparing the js time to the rails time works perfectly.

var year = 2000
var month = 10
month --
var day = 5
var date = (new Date(year, month, day).getTime() / 1000);
date
=> 970722000


Date.new(2000,10,5).to_time.to_i
=> 970722000 
like image 143
Jeff Caros Avatar answered Sep 27 '22 23:09

Jeff Caros


User date Format patterns for Jquery Date, for changing the format of date according to ruby date , or second option is convert ruby date format according to jquery , using strftime.

like image 31
Anil Yadav Avatar answered Sep 27 '22 23:09

Anil Yadav


You might try converting them both to their unix timestamps and comparing those. If you don't care about the hours, and simply the dates, it should work.

var year = 2001
var month = 9
var day = 14
var date = new Date(year, month, day);
<% @date = Date.today - 18.years %>
if ( date.getTime() > <%= @date.to_time.to_i %>) {
  // do something
}
like image 26
yez Avatar answered Sep 27 '22 22:09

yez


I'd use a library like Moment.JS to handle your date parsing needs on the client side. And then send the server something in a standard format like ISO8601 to ensure you don't have any problems in misintrepretation.

Epoch time will work as well, but as you've seen you have to carry the burden of ensuring that they're in the same units.

like image 38
Rich Seviora Avatar answered Sep 27 '22 23:09

Rich Seviora