What I receive from the front-end is this:
"date": "2021-06-04T22:00:00.000Z"
This is the dateTime in GMT+0. How can I now convert it to a Date object in my back-end so that it's 2021/06/05" (5th of June, midnight)?
Here's what I have so far:
CultureInfo culture = new CultureInfo("nl-BE");
...
var entity = _mapper.Map<HolidayDate>(h);
entity.Date = Convert.ToDateTime(entity.Date, culture);
_holidayDateRepository.Add(entity);
So I'm setting the culture to my culture (GMT +2). Then I'm mapping my front-end DTO to an entitiy object "HolidayDate" here. Then I want to alter the Date, which right now has the wrong value (GMT +0). How can I make it so that it will get the correct culture/GMT+ +2 date?
Do I do it here in my back-end code, or can I set in in my AutoMapper configurations or another way?
Try this method.
private static DateTime ToLocalTime(string utcDateTimeString, string timeZoneString)
{
var utcDateTime = DateTime.Parse(utcDateTimeString);
var utcDateKind = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
var timeZone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneString);
var localTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateKind, timeZone);
return localTime;
}
Usage;
public static void Main()
{
var utcTimeString = "2021-06-04T22:00:00.000Z";
var localDateTime = ToLocalTime(utcTimeString, "South Africa Standard Time");
Console.WriteLine(localDateTime);
}
List of timezone names. https://learn.microsoft.com/en-us/windows-hardware/manufacture/desktop/default-time-zones