Reputation: 1349
Hi folks im sure this is probably a simple question for alot of you. I have a a text field in a TD with a date "23/04/2015 9:23 PM" and I need that cell to simply to orange when its 30 minutes overdue and red if 60 minutes overdue.
I have this fiddle with an example of how the dates are laid out. But having no luck with the code. http://jsfiddle.net/s3328ffo/35/
Anyone have any idea where im going wrong here?
$('#timeTable tr td').each(function () {
var dtTd = new Date($(this).html());
var dtNew = new Date();
// 15 minutes is 900000 milliseconds
// getTime() doc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
if (dtTd.getTime() - dtNew.getTime() < 900000 && dtNew < dtTd) {
$(this).parent('tr').addClass('min15');
} else {
if (dtNew > dtTd) {
$(this).parent('tr').addClass('old');
}
}
});
Upvotes: 2
Views: 1411
Reputation: 2322
As @rich.okelly suggested, the dates are being parsed in MM/DD/YYYY format. To change the date to DD/MM/YYYY format, you could do something like this:
var dtSt = $(this).html().split(" ");
var dtAr = dtSt[0].split("/");
var dtTd = new Date(dtAr[1] + "/" + dtAr[0] + "/" + dtAr[2] + " " + dtSt[1]);
This will swap the month and day in the variable before parsing it as a date.
http://jsfiddle.net/IronFlare/s3328ffo/28/
EDIT: I know that this issue has already been resolved, but I knew my code was somewhat inefficient and longer than it had to be, so I couldn't help but attempt to improve upon it. I managed to shorten it quite a bit, and I have a feeling that this will significantly improve performance.
var dtSt = $(this).html().split("/");
var dtTd = new Date([dtSt[1], dtSt[0], dtSt[2]].join("/"));
Upvotes: 1
Reputation: 1349
Alright folks I got it working. I had to combine part of IronFlare's and rich.okelly's codes to get it to work like I needed. Thank you so much guys!
http://jsfiddle.net/mt8sf7gL/7/
$('#timeTable tr td').each(function () {
var dtSt = $(this).html().split(" ");
var dtAr = dtSt[0].split("/");
var when = new Date(dtAr[1] + "/" + dtAr[0] + "/" + dtAr[2] + " " + dtSt[1]);
console.log(when);
var now = Date.now();
if (now - when > 3600000) {
$(this).parent('tr').addClass('min60');
} else if (now - when > 1800000) {
$(this).parent('tr').addClass('min30');
}
});
Upvotes: 0
Reputation: 41767
Dates are tricky beasts.
I believe that your dates are being parsed in 'American format' eg MM/dd/yyyy.
Hence more things are going red than they should be.
See http://jsfiddle.net/mt8sf7gL/ for a working example, but js copied below for reference:
$('#timeTable tr td').each(function () {
var when = Date.parse($(this).text()); // This can be changed from .text() to read the value from an attribute ifyou do not wish to display the date in this format
var now = Date.now();
if (now - when > 3600000) {
$(this).parent('tr').addClass('old');
} else if (now - when > 1800000) {
$(this).parent('tr').addClass('min15');
}
});
Upvotes: 1