[SalesForce] How to get current date as per logged in user in Lightning Component

I tried to get current date using new Date() but it is returning date as in users laptop. Also tried $A.localizationService.formatDate(new Date(), $A.get("$Locale.dateFormat")). How to get date based on users timezone?

Time Zone of logged in user

Here expected date is 5th June but it's returning date from my local system.

enter image description here

Best Answer

The $Locale global value provider returns information about the current user’s preferred locale. You can try using $locale.timezone in Aura to get the time zone and perhaps use it along with new Date to get the Date similar to the current loggged in user's timezone.

Updated Snippet:

var timezone = $A.get("$Locale.timezone");
console.log('Time Zone Preference in Salesforce ORG :'+timezone);
var mydate = new Date().toLocaleString("en-US", {timeZone: timezone})
console.log('Date Instance with Salesforce Locale timezone : '+mydate);

var localDate = new Date();
console.log('Local Date in Your Laptop : '+localDate);
var timezone = localDate.getTimezoneOffset();

Updated Output:

updated Date

The offset -330 translates to UTC + 5:30 which is Asia/Kolkatta, if both your ORG and local Date is same, then it can mean only thing the timezone preference in your SALESFORCE ORG is Asia/Kolkatta. Kindly check your configurations.

Reference : https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/expr_locale_value_provider.htm

Note :

  • Though new Date().toLocaleString("en-US", {timeZone: "America/New_York"}) has native support in almost all the modern day browsers.
  • It is recommended to use a library such as Timezone.js or moment.js etc for wider browser support.
Related Topic