How to get the current datetime in CRM client side using Javascript.

I got the issue where I needed to get the datetime as per CRM logged in user timezone. I have written one more blog where we can do this at server side by hitting the org service Get date time as per current user time zone , but how to do that at client side??

Either we can hit the CRM services to get the timezone and calculate the time or we have one simple way to do that as below:

What exactly below code does?

This gets the current machine time and then converts the UTC datetime. after that we calculate crm user datetime by adding the current time zone offset minutes of logged in user.

How to get the offset minutes of the login user?

Xrm.Page.context.getTimeZoneOffsetMinutes();

////Please note: This method is available only after “CRM 2015 Update 1” version.

over all code is as below:

var date = new Date();

var utcDate = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());

var crmUserDateTime = new Date(utcDate.setMinutes(utcDate.getMinutes() + Xrm.Page.context.getTimeZoneOffsetMinutes()));

We can ever use jQuery date picker and simply pass the date in var date = new Date(“05/25/2017”);

var date = new Date(“05/25/2017”); // here we can pass multiple formated dates. and any date.

var utcDate = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds());

var crmUserDateTime = new Date(utcDate.setMinutes(utcDate.getMinutes() + Xrm.Page.context.getTimeZoneOffsetMinutes()));

Hope this helps 🙂

Happy learning.

Please follow my blog, so that whenever i create any blog you get notifications.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s