Lajith
Lajith

Reputation: 1867

ASP.NET Core UTC time to Local

I am using ASP.NET Core 5 and Entity Framework Core as my ORM. Am getting UTC time from an Angular application. But the user will be from only one country. So I decided to convert UTC time to Local—i.e India's timezone—while saving to the database.

My Questions:

  1. How can I configure the ASP.NET Core app to always convert UTC time to en-IN when storing to the database?
  2. Also, I need to convert the local time back to UTC when sending the data to the API.

Please any one suggest the application Local time is always en-IN, but hosted on same/different countries.

Please let me know how to convert UTC time to Local Time (en-IN) and vice versa

Upvotes: 2

Views: 12773

Answers (2)

Kavinda Senarathne
Kavinda Senarathne

Reputation: 2004

The Date.setMinutes() function expects a value between 0 and 59.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMinutes

I would grab the user's time zone offset and put the value in a cookie. How you craft the code depends on your app. If the user must login then I would grab the value when the user's login. If you are using ASP Identity then you can store the time zone offset as a claim. Then do the math on the server where Date functions are more robust.

Otherwise, you'll need to write a date.addMinutes function in JavaScript or use an existing library like Moment.

https://momentjs.com/

Upvotes: 0

Zhi Lv
Zhi Lv

Reputation: 21371

In asp.net core, the easiest way to convert a time to UTC is to call the static (Shared in Visual Basic) TimeZoneInfo.ConvertTimeToUtc(DateTime) method.

        DateTime dateNow = DateTime.Now;

        Console.WriteLine("Local date and time: " + dateNow);

        var kind = dateNow.Kind;
        Console.WriteLine("The date and time are {0} UTC.",
                           TimeZoneInfo.ConvertTimeToUtc(dateNow));

Then, to convert UTC to the time in any time zone that you designate, call the ConvertTimeFromUtc method.

        DateTime timeUtc = DateTime.UtcNow;
        try
        {
            TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
            DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
            Console.WriteLine("The date and time are {0} {1}.",
                              cstTime,
                              cstZone.IsDaylightSavingTime(cstTime) ?
                                      cstZone.DaylightName : cstZone.StandardName);
        }
        catch (TimeZoneNotFoundException)
        {
            Console.WriteLine("The registry does not define the India Standard Time zone.");
        }
        catch (InvalidTimeZoneException)
        {
            Console.WriteLine("Registry data on the India Standard Time zone has been corrupted.");
        }

More detail information, see Converting times between time zones and DateTime.ToUniversalTime Method (convert date time string to DateTime object).

Besides, you could also use JavaScript to convert the datetime between UTC time and Local time.

To convert UTC time to Local date time (with specific time zone) using JavaScript, you could try to use the Date.prototype.toLocaleString() method.

Sample code as below:

const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// British English uses day-month-year order and 24-hour time without AM/PM
console.log(event.toLocaleString('en-IN', { timeZone: 'UTC' }));
// expected output: 20/12/2012, 03:00:00

// Korean uses year-month-day order and 12-hour time with AM/PM
console.log(event.toLocaleString('ko-KR', { timeZone: 'UTC' }));
// expected output: 2012. 12. 20. 오전 3:00:00

console.log('USA time: '+ event.toLocaleString("en-US", {timeZone: "America/New_York"}))
// expected output: USA time: 2020-11-15T13:20:52.000Z 

console.log('India time: '+ event.toLocaleString("en-US", {timeZone: "Asia/Kolkata"}))
// expected output: India time: 2020-11-15T23:50:52.000Z

To convert local time to UTC time, you could try to use the Date Object toUTCString() method or the Date.UTC() method.

Edit:

Besides, ASP.NET Core MVC supports data exchange in Web APIs using input and output formatters. Input formatters are used by Model Binding. Output formatters are used to format responses.

You could refer to the following sample code to format the response data, it will convert the local datetime to the UTC time:

Create a custom datetime converter:

public class DateTimeConverter : JsonConverter<DateTime>
{
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        Debug.Assert(typeToConvert == typeof(DateTime));
        return DateTime.Parse(reader.GetString());
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ssZ"));
    }
}

Configure the custom converter (In ASP.NET Core 3.0 or later, the default JSON formatters are based on System.Text.Json):

        services.AddControllersWithViews().AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
        });

[Note] using above code, it just format the response data, instead of changing the input data.

For the input formatters, you could try to create a Custom Model Binding to change the datetime format.

Upvotes: 6

Related Questions