Comparing jQuery date to Rails date - javascript

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

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

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.

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
}

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.

To compare 2 dates for me u can use moment.js
With ur rails date create a moment date. Do the same with ur jquery date.
U can compare easily the 2 dates now.
If u need help see this post : moment-js-date-time-comparison

Related

Setting Date in the Future with Javascript

I am trying to generate a future date based on a previously set date, but I am getting strange output.
var today = new Date(),
expiration = (today.getTime() + (3*60*1000),
theFuture = new Date();
//setup future time
theFuture.setDate(expiration);
console.log(theFuture);
//outputs something like:
Tue Jan d) -2147483647 20:33:52 GMT-0500 (EST)
Why is the date malformed here?
Ultimately I want to compare the dates, but something isn't right here.
The argument to setDate is the day of the month, while the return value of getTime is the number of milliseconds since Jan 1 1970. So you're setting the day of the month to something like 1437007985574, which is almost 4 billion years in the future. You get a nonsensical result because the date formatting functions aren't designed to handle such large dates, and they're overflowing internally.
Since you're using getTime to get the time in milliseconds, you should use setTime to set it the same way:
var today = new Date(),
expiration = today.getTime() + (3*60*1000),
theFuture = new Date();
//setup future time
theFuture.setTime(expiration);
alert(theFuture);
getDate() returns day of the month (between 1 and 31). Thats why setDate results in a malformed date

Date subtraction returns unexpected result

I have some JavaScript that pulls dates out of two fields on my web page:
var StartDate = document.getElementById('StartDate');
var EndDate = document.getElementById('EndDate');
When I get these two dates I have the following snippet of code that performs the date subtraction:
var day = 1000*60*60*24;
var d1 = new Date(StartDate.value);
var d2 = new Date(EndDate.value);
var difference = (Math.ceil((d2.getTime() - d1.getTime()) / day))
Now is when the problem comes in. Say that my two dates are as such:
StartDate = 2013-05-01
EndDate = 2013-06-30
Using the calculator we get:
1372564800000 - 1367380800000 = 5184000000
5184000000 / 86400000 = 60 days
However, next let's use the following dates:
StartDate = 2013-10-01
EndDate = 2013-11-30
Again, using the calculator we get:
1385787600000 - 1380600000000 = 5187600000
5187600000 / 86400000 = 60.04166666666667 days
I'm just not sure how this is possible, I am using two identical date ranges. Both start days start on the first of a month with 31 days, and both end days end on the last day of a month with 30 days. When I put these date ranges into a MS Excel workbook I get the correct number of days:
=(EndCell-StartCell)
And I again get the 60 days for both sets of date ranges.
This seems to only happen when I cross into November of 2013. It doesn't happen when I cross into November of 2014, and I cannot find any other times when this happens. I know 2013 is gone, but my application will deal heavily with 2013 dates. Does anybody know of a reason why/how this is happening? Does anybody know of a better way to do date subtraction with JavaScript that will not cause this issue?

javascript: how to validate two dates for one month in javascript

I'm trying to compare two dates for exactly one month. I used the code below for the validation. Its working for this case:
from Date:1/5/2013 to Date:1/6/2013
but not working if we consider February month, e.g.:
fromDate:28/2/2013; toDate:31/3/2013;
Can you let me know the solution?
I tried the code below (source), but it's not working.
var fromDate = new Date(document.getElementById("Billing_From").value);
var toDate = new Date(document.getElementById("Billing_To").value);
fromDate.setMonth( fromDate.getMonth() + 1 );
if((fromDate-toDate) !=0)
{
alert("Please limit the date range to 1 month.");
}
Keep the following in mind.
The default format is MM/dd/yyyy.
In Javascript Date months are from 0(Jan) to 11(Dec).
This code is for comparing same dates of adjacent months. Example - 15th Feb, 2013 and 15th March, 2013.
What is you exact definition of month ?

JavaScript: Convert Day/Week Into Year

I have been using Stack Overflow for a number of months now, but this is my first post.
I require a function to convert a week number and and day of week into a dd/mm/yyyy format.
The date values i have to work with are in the format day/weekNumber. So for example: 3/43 converts to Wednesday 24 October 20XX. The year value will be the current year.
The day value starts at 1 (Monday).
I have found lots of functions on the internet (such as this, this and this). Some work with ISO 8601 dates, which i do not think will work for me. And i have not yet found one that works for me.
Thanks in advance,
This solution does require an extra library to be added, but I think it is really worth it. It is a momentjs library for manipulating dates and time. It is actively maintained and has a great documentation. Once you get the values for day and weekNumber (in our case 3 and 43), you should do as follows:
function formatInput(day, weekNumber){
var currentDate = moment(new Date()); // initialize moment to a current date
currentDate.startOf('year'); // set to Jan 1 12:00:00.000 pm this year
currentDate.add('w',weekNumber - 1); // add number of weeks to the beginning of the year (-1 because we are now at the 1st week)
currentDate.day(day); // set the day to the specified day, Monday being 1, Sunday 7
alert(currentDate.format("dddd, MMMM Do YYYY")); // return the formatted date string
return currentDate.format("dddd, MMMM Do YYYY");
}
I think this library might be useful to you later on and there are plenty of possibilities regarding date and time manipulation, as well as formatting options. There is also a great documentation written for momentjs.
So assuming you have the values of 3 and 43 separately, you can just do some simple maths on the first day of the current year:
Get 1st January Current Year
Add (43 * 7 + 3)
Something like this maybe:
var currentDate = new Date();
var startOfYear = new Date(currentDate.getFullYear(), 0, 1);//note: months start at 0
var daysToAdd = (43 * 7) + 3;
//add days
startOfYear.setDate(startOfYear.getDate() + daysToAdd);
Here is an example
EDIT
On second thoughts, I think I was wrong with your requirements. It seems you require a specific day of the week. Check this out for a better solution.
The problem is that it all depends on your definition of a week. This year starts on a sunday, so does that mean that 02/01/2012 (the first monday of this year) is the start of the second week?
My latest example will first find the start of the specified week, and then find the next occurrence of the specified day
According to ISO when dealing with week dates, the week starts on Monday and the first week of the year is the one that contains the first Thursday of the year. So for 2012, the first week started on Monday, 2 January and the first week of 2013 will start on Monday, 31 December 2012.
So if 3/43 is the third day of the 43rd week (which is the ISO date 2012-W43-3), then it can be converted it to a date object using:
function customWeekDateToDate(s) {
var d, n;
var bits = s.split('/');
// Calculate Monday of first week of year this year
d = new Date();
d = new Date(d.getFullYear(),0,1); // 1 jan this year
n = d.getDay();
d.setDate(d.getDate() + (-1 * n +( n<5? 1 : 8)));
// Add days
d.setDate(d.getDate() + --bits[0] + --bits[1] * 7);
return d;
}
console.log(customWeekDateToDate('3/43')); // 01 2012-10-24
Note that this uses dates, otherwise daylight saving changeovers may result in the wrong date.

JavaScript date objects UK dates

I have the following code
datePicker.change(function(){
dateSet = datePicker.val();
dateMinimum = dateChange();
dateSetD = new Date(dateSet);
dateMinimumD = new Date(dateMinimum);
if(dateSetD<dateMinimumD){
datePicker.val(dateMinimum);
alert('You can not amend down due dates');
}
})
dateSet = "01/07/2010"
dateMinimum = "23/7/2010"
Both are UK format. When the date objects are compared dateSetD should be less than dateMinimumD but it is not. I think it is to do with the facts I am using UK dates dd/mm/yyyy. What would I need to change to get this working?
The JavaScript Date constructor doesn't parse strings in that form (whether in UK or U.S. format). See the spec for details, but you can construct the dates part by part:
new Date(year, month, day);
MomentJS might be useful for dealing with dates flexibly. (This answer previously linked to this lib, but it's not been maintained in a long time.)
This is how I ended up doing it:
var lastRunDateString ='05/04/2012'; \\5th april 2012
var lastRunDate = new Date(lastRunDateString.split('/')[2], lastRunDateString.split('/')[1] - 1, lastRunDateString.split('/')[0]);
Note the month indexing is from 0-11.
var dateString ='23/06/2015';
var splitDate = dateString.split('/');
var month = splitDate[1] - 1; //Javascript months are 0-11
var date = new Date(splitDate[2], month, splitDate[0]);
Split the date into day, month, year parts using dateSet.split('/')
Pass these parts in the right order to the Date constructor.
Yes, there is problem with the date format you are using. If you are not setting a date format the default date that is used is 'mm/dd/yy. So you should set your preferred date formate when you create it as following when you create the date picker:
$(".selector" ).datepicker({ dateFormat: 'dd/mm/yyyy' });
or you can set it later as:
$.datepicker.formatDate('dd/mm/yyyy');
When you try to create a date object:
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Example:
dateSetD = new Date(dateSet.year, dateSet.month, dateSet.day);
Note: JavaScript Date object's month starts with 00, so you need to adjust your dateset accordingly.

Categories

Resources