Home > OS >  How to manage DataTime of a global dotnet application?
How to manage DataTime of a global dotnet application?

Time:11-30

I am planning a .NET application that will be used in different countries. This application contains a web API and a single page front end. The application will also use a database table with a datetime column. The values in the table will be for the UTC timezone.

I am confused about handling these values. My users may be in any country. Where can I convert the local time to UTC time? Database data goes via an API to the front end application. User data comes from a single page application to the database via web API.

CodePudding user response:

For the scenario you described, the best practice would be to keep the values in terms of UTC as they are returned from your API. For example, your API may return a result such as:

{
  "id": 123
  "timestamp": "2022-12-31T23:59:59.9999999Z"
}

The timestamp in that result is in ISO 8601 extended format (and is also RFC 3339 compliant). The Z at the end means the timestamp is in terms of UTC.

In the browser, you can use JavaScript to convert that timestamp to the user's local time. There are a large number of ways to do that, but the simplest would be:

new Date(timestamp).toString()

If you need to control formatting or convert to a time zone other than the user's local time zone, consider toLocaleString instead, or a JavaScript library such as Luxon or date-fns.

Alternatively, if your API must return local time values, then you will need to use the .NET TimeZoneInfo class to perform conversions (or NodaTime). You'll also need to know the time zone identifier for the user's browser, which you can get in JavaScript with the Intl API, as shown here.

CodePudding user response:

DateTime in C# as function like ToUniversalTime() and ToLocalTime(). See https://learn.microsoft.com/en-us/dotnet/api/system.datetime.touniversaltime?view=net-7.0

  • Related