Want to display date in QQ-YYYY format in Kendo Grid - model-view-controller

I am using Kendo Grid in MVC and I want to format a date column in QQ-YYYY format. Ex: if date is Jan 23 2021, it should display as 01-2021. I tried the below code but not working. Please help. My code is as below.
#(Html.Kendo().Grid(Model)
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.TeamRank).Title("Team Rank").Hidden();
columns.Bound(p => p.ETA).Title("Forecast").ClientTemplate("#=formatDate(ETA)#");
}
My formatDate function
'''
function formatDate(ETA) {
var CurrentQuarter = ((ETA.getMonth - 1) / 3) + 1;
return CurrentQuarter + "-" + ETA.getFullYear;
}
'''
Thanks

You can use the date parsing and formatting tools from Kendo.
function formatDate(ETA /* Jan 23 2021 */) {
var date = kendo.parseDate(ETA, "MMM dd yyyy");
var quarter = Math.floor((date.getMonth() + 3) / 3);
var formattedDate = kendo.toString(quarter, "00") + "-" + date.getFullYear();
return formattedDate;
}
console.log(formatDate("Jan 23 2021"));

Related

In chart.js how can I change the x axis on my line \chart from January-December to October-September? Basically, fiscal year instead of calendar year

My line chart has multiple lines, one for each year. The points on each line have the correct date, but the chart starts at January instead of October and I have been unable to figure out how to make it start at October. Even though the point dates are correct, for example, 10/01/2014 or 9/30/2015, I have changed the formatted date years to all be the same year so all the lines will show in the same month.
Below are the generated chart and associated code.
//process the data for all charts except dredge depth as it will function differently
if (reportType !== "dredgedepth") {
yValueKey = "DAY_VALUE";
xValueKey = "Date";
var CumulativeDayTotal = 0;
var formattedDate, _date; code:
var data, lineColor, monthName;
var chartPlaceHolders = "";
//loop through each year to build our objects needed for the chart
$.each(jsonData.results, function (i, row) {
data = row.dt;
CumulativeDayTotal = 0
yAxis = [];
$.each(data, function (i, row) {
CumulativeDayTotal = parseInt(row[yValueKey]) + parseInt(CumulativeDayTotal);
//if not a cumulative report then set dates to be in the same year so chartjs will stack our lines
//instead of spreading across multiple years, this way it reads it as the same year so we can get functionality
formattedDate = row["DATE_F"];
if (nsData.myChartFormat !== "cumulative") {
formattedDate = moment(formattedDate).year(2016);
}
formattedDate = formatDate(formattedDate);
yAxis.push("{ y: " + CumulativeDayTotal + ", x: '" + formattedDate + "'}");
});
//create color for each new line/year
lineColor = dynamicColors(i);
chartPlaceHolders += '{label:"';
if (nsData.myChartFormat === "fiscal") {
chartPlaceHolders += 'FY ';
}
chartPlaceHolders += row.year + '", data:[' + yAxis + '],' +
'fill: false,' +
'lineTension: 0.1,' +
'backgroundColor: "' + lineColor + '",' +
'borderColor: "' + lineColor + '",' +
'borderCapStyle: "butt",' +
'borderDash: [],' +
'borderDashOffset: 0.0,' +
'borderJoinStyle: "miter",' +
'pointBorderColor: "rgba(75,192,192,1)",' +
'pointBackgroundColor: "#fff",' +
'pointBorderWidth: .2,' +
'pointHoverRadius: 1,' +
'pointHoverBackgroundColor: "rgba(75,192,192,1)",' +
'pointHoverBorderColor: "rgba(220,220,220,1)",' +
'pointHoverBorderWidth: 0,' +
'pointRadius: 2,' +
'pointHitRadius: .75,' +
'pointHitDetectionRadius : .75' +
'},';
});
}
//remove last comma from string
chartPlaceHolders = chartPlaceHolders.replace(/,\s*$/, "");
chartPlaceHolders = "[" + chartPlaceHolders + "]";
var initFields = eval("(" + chartPlaceHolders + ")");
//call newly created elements into a variable to pass along to the other functions
var ctx = $("#primaryChart")[0].getContext("2d");
var myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: initFields
},
options: {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: yAxisLabel
}
}],
xAxes: [{
type: 'time',
unit: 'month',
time: {
unit: 'month',
tooltipFormat: tooltipDateFormat,
displayFormats: {
millisecond: xAxisDateFormat,
second: xAxisDateFormat,
minute: xAxisDateFormat,
hour: xAxisDateFormat,
day: xAxisDateFormat,
week: xAxisDateFormat,
month: xAxisDateFormat,
quarter: xAxisDateFormat,
year: xAxisDateFormat
}
},
scaleLabel: {
display: true,
labelString: xAxisLabel
}
}]
}
}
});
The solution was to get the fiscal years correct:
$.each(data, function (i, row) {
CumulativeDayTotal = parseInt(row[yValueKey]) + parseInt(CumulativeDayTotal);
// MLP 12/22/16: If not a cumulative report then set dates to be in the same year (2016)
// so chartjs will stack lines instead of spreading across multiple years. This was Austin
// Martin's code. I assume he chose 2016 because it is a leap year and will include
// February 29 in case the user selects a date range that includes Feb 29.
formattedDate = row["DATE_F"];
if (nsData.myChartFormat !== "cumulative") {
formattedDate = moment(formattedDate).year(2016);
}
// MLP 12/22/16: If fiscal chart, set October 1 through December 31 to 2015
// so char will show October through September instead of January through December.
Here:
if (nsData.myChartFormat === "fiscal") {
if (moment(formattedDate).format("YYYY/MM/DD") >= "2016/10/01") {
formattedDate = moment(formattedDate).year(2015);
}
}
// MLP 12/13/16: format date to UTC MM/DD/YYYY using momentJS because the JavsScript
// Date function converts dates to the local time zone.
formattedDate = formatDateUtc(formattedDate);
yAxis.push("{ y: " + CumulativeDayTotal + ", x: '" + formattedDate + "'}");
});

How to disable past date in daterangepicker?

I using two date selected daterangepicker. this working perfect but how to disable past date. below is my code
js/site/daterange/moment.min.js">
<script type="text/javascript" src="<?php echo base_url();?>js/site/daterange/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/site/daterangepicker.css" />
<script type="text/javascript">
$(function() {
$('input[name="checkin"],input[name="checkout"]').daterangepicker({
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
}
});
$('input[name="checkin"],input[name="checkout"]').on('apply.daterangepicker', function(ev, picker) {
//$(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
$('#checkin').val(picker.startDate.format('MM/DD/YYYY'));
$('#checkout').val(picker.endDate.format('MM/DD/YYYY'));
});
$('input[name="checkin"],input[name="checkout"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
});
this is easy way to solve the problem
$('input[name="daterange"]').daterangepicker({
minDate:new Date()
});
I had the same issue. I checked http://www.daterangepicker.com/#options and seems to me minDate would do the job.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){ dd='0'+dd }
if(mm<10){ mm='0'+mm }
var today = dd+'/'+mm+'/'+yyyy;
$('input[name="daterange"]').daterangepicker({
minDate:today
});
So as far as i can see from your code you want to disable dates that are in the past so there are multiple ways to do such a thing but the easiest of them in my opinion would be to get the current date on document load and set that as the start date for your date range picker.
http://www.daterangepicker.com/#options should give you the example explaining the startDate syntax to do the same and the code to find the current date in the said format can be show as below:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){ dd='0'+dd }
if(mm<10){ mm='0'+mm }
var today = dd+'/'+mm+'/'+yyyy;
Here today stores the string form of the format you need and can be set to the startDate attribute.

How to use local html5 storage to save grid preferences in Kendo Grid

My grid is:
#(Html.Kendo().Grid<Stuff>()
.Name("Grid")
.DataSource(source => source.Ajax().Events(events=>events.Error("onError"))
.Events(events=>events.RequestEnd("onRequestEnd"))
.Model(model =>
{
model.Field(p => p.PurchaseQuantity).Editable(false);
model.Field(p => p.PurchasePrice).Editable(false);
})
.Read("GetData", "Data"))
.Columns(columns =>
{
columns.Bound(o => o.PurchaseQuantity).Width(100);
columns.Bound(o => o.PurchasePrice).Format("{0:C}").Width(100);
})
.Sortable()
.Pageable(page=> page.PageSizes(new int[] { 10, 20, 50, 100 }).Refresh(true))
.Filterable(filterable => filterable.Extra(false))
.Events(boo=>boo.DataBound("onTest"))
.HtmlAttributes(new { style = "width:850px" })
)
and the javascript used to load data is:
<script type="text/javascript">
var storage = window.localStorage;
var storageLoaded = false;
function onError() {
$("#Grid").data("kendoGrid").dataSource.cancelChanges();
}
function onTest() {
if (!storageLoaded) {
console.log('loading size from storage ' + storage.pageSize);
storageLoaded = true;
console.log('marked storage loaded');
$("#Grid").data("kendoGrid").dataSource.pageSize(storage.PageSize);
console.log('set pagesize from storage ' + storage.pageSize);
var pagesize = $("#Grid").data("kendoGrid").dataSource.pageSize();
console.log('page size is ' + pagesize);
}
}
function onRequestEnd(e) {
if (storageLoaded) {
var pagesize = $("#Grid").data("kendoGrid").dataSource.pageSize();
storage.pageSize = pagesize;
console.log('setting size to storage ' + storage.pageSize);
}
}
firebug console shows:
loading size from storage 50 / marked storage loaded / set pagesize from storage 50 / page size is 10
Questions:
Why does the pagesize not save after set?
Is there a better way to accomplish this?
Is there a way to attach to the pagesize selector instead of using requestEnd?
Found a solution. Make the grid .AutoBind(false)
then
$(document).ready(function () {
storageLoaded = true;
$("#Grid").data("kendoGrid").dataSource._pageSize = storage.pageSize;
$("#Grid").data("kendoGrid").dataSource.read();
});
now this is making use of an _ variable inside the datasource which could break at any point in the future, but for now it does work.
I removed the databound event completely, a friend at Telerik was most helpful in getting me to the solution.
Hoping that in the future there will be something like:
.Pageable(page=> page.PageSizes(true).Refresh(true).Sticky("gridPageSizeDefault")
which will store the value in html5 local storage using the gridPageSizeDefaultkey.

kendo ui grid row how to set background color?

I need to change the row color of a kendo ui grid depending on a particular condition. I am using server side bindings with MVC. My code is as follows,
var grid = Html.Kendo().Grid<AllocateCOESGridViewModel>();
grid.Name("AllocateResultGrid")
.RowAction(row =>
{
if (row.DataItem.COESNo == 13054915)
{
row.HtmlAttributes["style"] = "background:blue";
}
else
{
row.HtmlAttributes["style"] = "background:red";
}
})
.Columns(columns =>
{
columns.Bound(s => s.COESNo).Title(#Allocate.COESGridHeading);
columns.Bound(s => s.Street).Title(#Allocate.StreetGridHeading);
columns.Bound(s => s.Suburb).Title(#Allocate.SuburbGridHeading);
columns.Bound(s => s.Postcode).Title(#Allocate.PostcodeGridHeading);
columns.Bound(s => s.InspectorName).Title(#Allocate.InspectorGridHeading);
columns.Bound(s => s.COESNo).Title(#Allocate.AllocateGridHeading + "<input type ='checkbox' id ='SelectAll' />").ClientTemplate("<input type ='checkbox' data-id='#= COESNo #' class='allocate' />").Sortable(false);
});
The grid works but no row colors at all? no blue or red.. I just get the standard white and grey.. any thoughts?
Thanks
This is how I got this to work, just wondering if there is any other options, as looping through the grid seems like a not so good idea... especially if the grid is long
var grid = $("#AllocateResultGrid").data("kendoGrid");
grid.bind("dataBound", updateGridRows);
updateGridRows: function()
{
dataView = this.dataSource.view();
for (var i = 0; i < dataView.length; i++)
{
if (dataView[i].Selected == false)
{
var uid = dataView[i].uid;
$("#AllocateResultGrid tbody").find("tr[data-uid=" + uid + "]").addClass("customClass");
}
}
}
I added the customClass in my stylesheet
I had the same issue, let me know if you find one without loops!
var grid = $("#AllocateResultGrid").data("kendoGrid");
var data = grid.dataSource.data();
$.each(data, function (i, row) {
if (row.Selected == false)
$('tr[data-uid="' + row.uid + '"] ').addClass("customClass");
}

datepicker JQuery Validations and Format

I am using the following for datepicker in Jquery to format the date display in dd/mm/yy format and also I want the user not to select future date.Only one thing is working at a time.
<script type="text/javascript" language ="javascript" >
$(function () {
var date = new Date();
var currentDate = date.getDate();
var currentMonth = date.getMonth();
var currentYear = date.getFullYear();
$(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });
$(".datepicker").datepicker({ maxDate: new Date(currentYear, currentMonth, currentDate) });
});
</script>
How do make, both the dateformat and disable the future dates to work simultaneously. I am missing single bit, I don't know how to club this two validations or requirements togather.
Any answers Please?
Thank you.
I had a similar requirement for my code with a hire date. Here's how I did it:
$('#hireDate').datepicker({
dateFormat: 'dd/mm/yy',
maxDate: new Date(currentYear, currentMonth, currentDay)
});
The user can still enter a future date manually and weasel around your date picker. We had this problem on a production system.
If you want to additionally validate the date using the validation plugin, try this:
/**
* Requires Datepicker and Validator
*
* Params:
* 0...dateformat. see datepicker
* 1...date. Value "0" is "today"
* 2...(optional). date to display. will be automatically filled if 0 and 1 are set.
* usage:
* myfield: { maxDate: ['m/d/yy', 0] }
*/
jQuery.validator.addMethod("maxDate",
function(value, element, params) {
if (!params[0])
throw 'params missing dateFormat';
if (typeof(params[1]) == 'undefined' )
throw 'params missing maxDate';
var dateFormat = params[0];
var maxDate = params[1];
if (maxDate == 0) {
maxDate = new Date();
maxDate.setHours(0); // make it 00:00:0
maxDate.setMinutes(0);
maxDate.setSeconds(0);
maxDate.setMilliseconds(0);
}
if (typeof(params[2]) == 'undefined' )
params[2] = $.datepicker.formatDate(dateFormat, maxDate);
try {
var valueAsDate = $.datepicker.parseDate( dateFormat, value )
return (valueAsDate < maxDate);
} catch (x) {
return false;
}
},'Must be greater than {2}.');
$("#myform").validate({
rules: {
datepicker : {
maxDate ['m/d/yy', 0]
}
}
});
HTML:
<input name="datepicker" class="datepicker" type="text"/>

Resources