Date Formatting in Kendo Grid and Handling Timezone

 In Kendo Grid, the dates are formatted to 'Mon Feb 01 2021 02:03:04 GMT+0530 (India Standard Time)'. To convert to a specific format or specific time zone we can try below options. 

"kendo.parseDate(data.CreatedDate)" -- to keep the date data type same and convert to the local browser's timezone

"kendo.parseDate(data.CreatedDate, 'MM-dd-yyyy')" -- to keep the data data type and format the data type to the local browser's timezone

"kendo.toString(kendo.parseDate(data.CreatedDate), 'MM/dd/yyyy hh:mm:ss tt" -- to format the date to string format with whatever timezone it has received from the server. This converts hours into 12 hour format. when you replace hh with HH it will give 24 hour format. 

For converting to specific timezone, we can try the below..

"CreatedDate.toLocaleString("en-US", {timeZone: "America/New_York"})" -- Works only in Chrome and Forefox. For IE, it throws an error. 

"CreatedDate.toLocaleString("en-US", {timeZone: "IST"})" -- Indian Time

"CreatedDate.toLocaleString("en-US", {timeZone: "PST"})" -- Pacific Time

"CreatedDate.toLocaleString("en-US", {timeZone: "UTC"})"


In case nothing gets worked out, you need to depend on third party/external library named "moment.js". 

It comes up with couple of different flavors. For simple cases like parsing and formatting, you can use moment js only. For time zone conversions, you can use moment time. 

These 2 files work for older versions of browsers also. 

function toPSTDate(dateVal, fmt) {

    if (dateVal == null)

        return "";

    return moment(dateVal).tz("America/Los_Angeles").format(fmt);

}

For modern browsers, you can just use one library called luxon js that has both parsing and time zone conversions. You can get more details at "https://momentjs.com/". 

luxon.DateTime.fromJSDate(dateVal).setZone("America/Los_Angeles").toFormat('MM/dd/yyyy hh:mm:ss a')

Comments

Popular posts from this blog

Base 64 encoding and decoding

LINQ Queries with GROUP BY, INNER JOIN, COUNT and SUM: Examples

How to write Custom delete Confirmation Modal for Kendo Grid in MVC: