check if date is today`s date in kendo grid column - javascript

I am doing displaying dates in a column, if it is today`s date, there should be css class applied, if not, just date should be displayed. I tried to solve it this way:
template: "#if(Date == new Date()) {#<div class='todayClass'>#= kendo.toString(kendo.parseDate(Date, 'yyyy-MM-dd'), 'dd-MM-yyyy') #</div>#} else{#= kendo.toString(kendo.parseDate(Date, 'yyyy-MM-dd'), 'dd-MM-yyyy') #}#",
but I get an error: "Date is not a constructor", does anyone know how to solve it? Thanks

You can create a function for the dataBound event that iterates through the grid's rows and check for that specific field.
function checkDates() {
var currentDate = new Date();
currentDate = currentDate.setHours(0, 0, 0, 0); // eliminate the time from the date
dataView = this.dataSource.view();
for (var i = 0; i < dataView.length; i++) {
// check if the fields match and apply a class to the row if so
var mydate = dataView[i].Date.setHours(0, 0, 0, 0); // eliminate the time from the date
if (mydate == currentDate) { // compare dates
var uid = dataView[i].uid;
$("#grid tbody").find("tr[data-uid=" + uid + "]").addClass("yourClass");
}
}
}
You may need to make the date formats match, but that another issue (not hard to solve)
EDIT
I have addressed the date formatting for you, this way it certainly works, as you can confirm in this fiddle

Related

Disabling future dates in bootstrap datepicker without using startDate and endDate

I wanted to have a datepicker that would disable not only past dates, but also future dates. All of the answers on Stack Overflow regarding similar questions all point towards using startDate and endDate. But what if you're using a version of datepicker that doesn't have those options? For example, bootstrap-datepicker.js.
The main obstacle was correctly setting the ending cut-off date (at least for me). I found that the method that should work for all datepickers is to directly add or subtract the date in the date declaration when initializing it, because this is a JS operation and bootstrap datepickers are based on JS:
new Date(checkin.date.getFullYear(), checkin.date.getMonth(), checkin.date.getDate() + 6, 0, 0, 0, 0);
Note how I have the + 6 next to the date as I want the end date to be one week after the chosen start date, and to disable everything after that.
Thus, the full code for disabling everything before and everything one week after the chosen start date is:
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
var checkin = $('.date-group').datepicker({
onRender: function (date) {
}
}).on('changeDate', function (ev) {
//if (ev.date.valueOf() > checkout.date.valueOf()) {
var newDate = new Date(ev.date)
newDate.setDate(newDate.getDate() + 0); // automatic date offset for end date (currently 0)
checkout.setValue(newDate);
//}
checkin.hide();
checkout.show();
$('.end-date-group')[0].focus();
}).data('datepicker');
var checkout = $('.end-date-group').datepicker({
onRender: function (date) {
var cap = new Date(checkin.date.getFullYear(), checkin.date.getMonth(), checkin.date.getDate() + 6, 0, 0, 0, 0);
if (date.valueOf() < checkin.date.valueOf()) {
return 'disabled';
}
else if (date.valueOf() > cap.valueOf()) {
return 'disabled';
}
}
}).on('changeDate', function (ev) {
checkout.hide();
}).data('datepicker');
The resulting datepicker:
You can also do the same for month and year should the need arise.
For reference, the specific datepicker that I used is bootstrap-datepicker.js.
Hopefully this helped. Cheers!

Add 1 day to date from spreadsheet via Google App Script / Javascript- Month Keeps Reseting to current month

I am trying to set up a Google App Script function that grabs a date (formatted dd/mm/yy) from the last column of a spread, and creates a new column with the date + one day.
I have seen previous solutions and tried to use the same, i.e.newDate.setDate(lastDate.getDate()+1) but have had issues getting the value formatted correctly in the script. This is a variation of my code that I'm using to loop through for a year's worth of values to see what I get:
for (var i=0;i<365;i++){
var lastRow = outputSheet.getLastRow();
var newDate = new Date();
var lastDate = outputSheet.getRange(lastRow,1).getValue();
var newDateRng = outputSheet.getRange(lastRow+1,1);
Logger.log(lastDate + 1, typeof lastDate, typeof (lastDate + 1));
newDate.setDate(lastDate.getDate());
Logger.log(newDate);
newDate.setDate((newDate.getDate() + 1));
Logger.log(newDate);
var newDateFormatted = Utilities.formatDate(newDate, ss.getSpreadsheetTimeZone(), "dd/MM/YY");
Logger.log(newDateFormatted);
newDateRng.setValue(newDateFormatted);
}
With a start date of "01/03/2020", I get the following behaviour:
01/03/2020
02/05/2020
03/05/2020
...
31/05/2020
01/06/2020
02/05/2020
03/05/2020
...
31/05/2020
01/06/2020
02/05/2020
...
etc. All the way through the year. Although the day increase, the month seems to reset after the first day of the month.
As a note, I am specifically looking to pick the date off of the spreadsheet rather than using new Date as today and new Date +1 as tomorrow.
Thanks
You need to use a different variable in the loop otherwise you will always return to the same month.
Also avoid using strings for the result, keep date objects and display it properly.
The code goes like this :
function otherTest(){
var lastDate = SpreadsheetApp.getActiveSheet().getActiveCell().getValue();
var date = new Date(lastDate); // create new date object
var result = [];
for (var i=0;i<365;i++){
date=new Date(date).setDate(new Date(date).getDate()+1)
Logger.log('date='+new Date(date))
result.push([new Date(date)]);
}
SpreadsheetApp.getActiveSheet().getRange(1,2,result.length,1).setValues(result).setNumberFormat('dd/MM/yyyy');
}

Trying to remove all the passed dates

I have an array with many dates, they are not in the date type but string like: "2016-08-12" for example. Then what I would like to do is to remove all dates that we already have passed. So therefor im trying to compare them to todays date and then remove it if its passed. Using typescript by the way.
my array, named datoArray, looks like this:
["2016-08-02", "2016-08-11", "2016-08-22", "2016-09-10"]
just with a lot more of the same...
then here's what I try to do:
for(var i = 0; i < this.datoArray.length; i++){
this.skoleAar = parseInt(this.datoArray[i].slice(0,4))
this.skoleMaaned = parseInt(this.datoArray[i].slice(5,8))
this.skoleDag = parseInt(this.datoArray[i].slice(8,10))
if(this.skoleAar < dagensAar){
this.datoArray.splice(i, 1);
}
if(this.skoleAar == dagensAar && this.skoleMaaned < dagensMaaned){
this.datoArray.splice(i, 1);
}
if(this.skoleAar == dagensAar && this.skoleMaaned == dagensMaaned && this.skoleDag < dagensDag){
this.datoArray.splice(i, 1);
}
}
the "dagensAar", "dagensMaaned" and "dagensDag" variables im getting from another function that works. If i "console.log" the variables it prints out int values like 2016 for the year and 8 for the month if i take from the start of the array, and for the "dagensAar", "dagensMaaned" and "dagensDag" it prints 2016 11 20, which is todays year, month and day. all is in Int type, so what im not getting here is why my "if" doesnt work? It seems like there is something wrong with the way i compare the, but i thought this was the way to compare int values?
If the dates are in ISO-8601 format then you can simply filter using Date.parse().
var dates = ["2016-08-02", "2016-08-11", "2016-08-22", "2016-09-10", "2016-12-15"];
function removePastDates(data) {
var today = new Date();
console.log('Initial state: ' + data);
var modified = dates.filter(function(dateString) {
return Date.parse(dateString) >= today;
});
console.log('Final state: ' + modified);
return modified;
}
var newDates = removePastDates(dates);
Your dates seem to be RFC compliant, meaning they can be directly fed into a new Date object. Simply compare to today and filter by that:
var today = new Date()
var futureDates = this.datoArray.filter(d => new Date(d) >= today)
(pre-ECMA6:)
var today = new Date()
var futureDates = this.datoArray.filter(function (d) {
return new Date(d) >= today;
})
I think the problem is not related to the dates.
I think the problem is that you are removing items from the array while looping the same exact array.
You should maybe try looping from the end of the array to the beginning or just save the indexes that you need to remove and later do the actual removing.
Keep in mind that when you remove an item you change the index of every item in the remaining of the array - maybe you should start removing from the greatest index so it will not confuse you.

Angular UI Grid date not formatting properly

I am using Angular's UI Grid to display a number of columns, but I cannot get the date column to format properly.
It is appearing as /Date(1451346632162-0000)/, etc.
I am trying to filter it in my gridOptions, but am having no luck:
// Removed Unrelated Column Defs
$scope.gridOptions.columnDefs = [
{ name: 'Date', field:'DateAdded',
/* First filter attempt */ cellTemplate: "<div>{{COL_FIELD | date:'dd-MM-yyyy' }}</div>",
/* Second Filter Attempt */ cellFilter:"date:'dd-MM-yyyy'"
}
I've tried variations of these that I found in the documentation with no luck - cellFilter: "date" and cellFilter: "longDate"
Any idea why these filter attempts are not working and the date is still appearing in this format?
I haven't been able to figure out what is stopping the regular filtering from working on the JSON date field, but here is the workaround I am using in the meantime (in case anyone has similar issues):
function formatDates(data) {
for (var i = 0; i < data.length; i++) {
var currentValue = data[i].DateAdded
var dateString = currentValue.substr(6);
var currentTime = new Date(parseInt(dateString));
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var date = month + "/" + day + "/" + year;
data[i].DateAdded = date;
}
}
If anyone has any idea what is stopping the regular filtering from working please post. Thanks.
Assure that you are actually using a Date object. If you're receiving the data from a database, it may not be a Date. When you query the database on the client side, you may need to do as follows: data.map(function(datum){ datum.DateAdded = new Date(datum.DateAdded) }).
This assures all dates are proper date objects.

Need explanation of this Date Processing function

Could anyone please explain the below code to me?
For example, i would like to set Today's date to today (21st of November, 2012) and the end date to the 3rd of December.
The reason for this is because i want to loop through a list of items, determine whether they are in the "past", "present" or "future" and assign a class to them accordingly.
I hope this makes sense! Any help is greatly appreciated and much welcomed!
function daysTilDate(expiredate){
expiredate ="12/"+expiredate+"/2012";
var thisDay=new Date(expiredate);
var CurrentDate = new Date();
var thisYear=CurrentDate.getFullYear();
thisDay.getFullYear(thisYear);
var DayCount=(thisDay-CurrentDate)/(1000*60*60*24);
DayCount=Math.round(DayCount);
return DayCount;
}
You can simplify the method like below if you want to calculate the days to an expire date. Please note that if you don't specify a test date, it'll take the current date as the test date.
​function ​daysTilData(expireDate, testDate) {
if(typeof testDate === "undefined"){
testDate = new Date(); // now
}
var diff = expireDate - testDate;
// minus value meaning expired days
return Math.round(diff/(1000*60*60*24));
}
alert(daysTilData(new Date("12/31/2012")));
// result 40
alert(daysTilData(new Date("12/31/2012"), new Date("1/12/2013")));
// result -12
Here's a line by line explanation.
The function declaration...
function daysTilDate(expiredate){
Takes the parameter expiredate sets it equal to the same value with "12/" prepended and "/2012" appended. so if the value of expiredate was "10", the new value is now "12/10/2012"...
expiredate ="12/"+expiredate+"/2012";
Instantiates a new Date object named thisDay using the expiredate string...
var thisDay=new Date(expiredate);
Instantiates a new Date object named CurrentDate, using the default constructor which will set the value equal to today's date...
var CurrentDate = new Date();
Gets just the Year segment from CurrentDate (which was earlier set to today's date)...
var thisYear=CurrentDate.getFullYear();
Gets the Year segment from thisDay (which was earlier set to "2012")...
thisDay.getFullYear(thisYear);
Gets the difference between thisDay and CurrentDate, which is in milliseconds, and multiplies that by 1000*60*60*24 to get the difference in days...
var DayCount=(thisDay-CurrentDate)/(1000*60*60*24);
Rounds the previously calculated difference...
DayCount=Math.round(DayCount);
Returns the difference between today and the passed-in day in December 2012...
return DayCount;
}
Note that the 2 lines that get the year segments are extraneous, because those values are never used...
I am not going to review the code, but I can answer your question of "I want to loop through a list of items, determine whether they are in the past, present, or future".
First, you want to construct your target date. If it's "now", just use new Date(). If it's a specific date, use new Date(dateString).
Second, Date objects in JavaScript have various members that return the date's characteristics. You can use this to compare dates. So, let's say you have your date strings in an array:
function loopDates(targetDateString, myDates) {
var targetDate, nextDate, status, ix;
targetDate = new Date(targetDateString);
for (ix = 0; ix < myDates.length; ++ix) {
nextDate = new Date(myDates[ix]);
if (nextDate.getFullYear() < targetDate.getFullYear()) {
status = "past";
} else if (nextDate.getFullYear() > targetDate.getFullYear()) {
status = "future";
} else {
// Year matches, compare month
if (nextDate.getMonth() < targetDate.getMonth()) {
status = "past";
} else if (nextDate.getMonth() > targetDate.getMonth()) {
status = "future";
} else {
// Month matches, compare day of month
if (nextDate.getDate() < targetDate.getDate()) {
status = "past";
} else if (nextDate.getDate() > targetDate.getDate()) {
status = "future";
} else {
// Day matches, present
status = "present";
}
}
}
console.log("Date " + myDates[ix] + " is " + status + " from " + targetDateString);
}
}
loopDates("11/17/2012", ["11/16/2012", "11/17/2012", "11/18/2012"]);
This will log:
Date 11/16/2012 is past from 11/17/2012
Date 11/17/2012 is present from 11/17/2012
Date 11/18/2012 is future from 11/17/2012
Working jsFiddle here.
If you want to work with a comprehensive Date class, use DateJS, an open source JavaScript date and time processing library with some impressive features.

Categories

Resources