Home > Blockchain >  How to get current time of particular country in nopcommerce 4.5?
How to get current time of particular country in nopcommerce 4.5?

Time:06-24

I want current time of India country in nopcommerce 4.5.

I used the following code for getting the current date time, i.e. DateTime.UtcNow in this line of code date is coming perfect, but according Indian time is not showing - it showing some other countries only.

For ex: in India, right now 19-06-2022 05:57 PM is happening but in database it storing 2022-06-19 12:23:44.0000000.

Is there any configuration setting for set country time or anything else?

CodePudding user response:

First, check the time and zone of your server. If the time is correct with the zone, you can convert it to the time of any other country.

There is no method to find out the current time of any country directly in NopCommerce. However, with the DateTimeHelper class, you can convert an UTC time into a user's current zone time or vice versa.

Method 1:

var destinationDateTime = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
var userTime = await _dateTimeHelper.ConvertToUserTimeAsync(DateTime.UtcNow, DateTimeKind.Utc, destinationDateTime);

Method 2:

var userTime = await _dateTimeHelper.ConvertToUserTimeAsync(DateTime.UtcNow, DateTimeKind.Utc);

Note: For method 2, if the store has permission (datetimesettings.allowcustomerstosettimezone setting) to select time zone for the customer and if the customer selects India as his time zone then he will be able to see Indian time all the time. And if he does not have permission to select the time zone, then he can see all the time in the default time zone of the store.

CodePudding user response:

You can use system.timezoneinfo class to get all the available Standard timezones and convert the current time to that time zone time. In your case it could be

var indiaTimeZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
var indiaTime = TimeZoneInfo.ConvertTime(DateTime.UtcNow, indiaTimeZone);

To check all the available time zone you can do

var zones = TimeZoneInfo.GetSystemTimeZones();
foreach (TimeZoneInfo zone in zones)
{
     Console.WriteLine(zone.Id);
}

Check this question for more info.

CodePudding user response:

it showing some other countries only.

The system is storing the date in UTC actually. If you compare UTC and Indian time, you'll see the difference matches with your example.

As for your problem, check out the DateTimeHelper class in Nop.Services\Helpers. There are a number of methods there you can use to get the current system time, or to convert time to and from UTC/User time.

  • Related