I'm programming a web application that clients can make appointments and choose a time: e.g: the admin has set the appointment times from 8 AM till 8 PM based on his own timezone (users timezoneId are saved in the database ) admin timezone: 3:30 There is 05:30 time difference between this client and admin . a client visits the site and tries to make an appointment for tomorrow from 10 AM to 10:30 AM. the client wants 10 AM based on his/her own timezone if we compute it based on the admin timezone 10 AM would be 3:30PM till 4:00 PM
- what datatype I have to use for saving time in DB (SQL server) DateTime or datetimeoffset?
- is there any implementation service for converting from another time zone to another? ( i have used timezoneinfo and DateTime convert built-in methods but all of them had problems)
- is daylight saving an important thing?
when I use convert methods (
TimeZoneInfo.ConvertTimeFromUtc()
)it considers daylight saving but when I use this method(TimeZoneInfo.ConvertTimeToUtc()
) I think it doesn't consider daylight saving. I don't know that is my system design is correct or not isn't it better to save all times in the 00:00 timezone even with admin configs? I'm so confused can someone help me? I have tried DateTime and datetimeoffset built-in methods and also timezoneinfo built-in methods but I couldn't handle it
CodePudding user response:
datetimeoffset
includes both date and time including the offset from the UTC. so you can store the specific time zone time.
NodaTime by sir Jon Skeet is a very good library to solve timezone-related problems, I have personally used it. you can also refer TimeZoneConverter library.
I personally prefer storing the UTC DateTime in the database and shows the time specific to the user's time zone in such scenarios.
Defnility Daylight Saving Time is a very important factor to be considered when working across different timezone.
you have to do testing around different timezones, DST cases. I have personally used the library Bogus for generating different times during my testing.
CodePudding user response:
Finally i solved my problem .
now i use datetime instead of datetimeoffset.
I use DateTime.UtcNow()
method to save current time in save changes.
I save user TimezoneId in database
i wrote 2 extension methods for datetime converters :
`
public static DateTime ToUserTime(this DateTime targetTime, string timeZoneId)
{
var timezone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
return TimeZoneInfo.ConvertTimeFromUtc(targetTime, timezone);
}
public static DateTime ToUtc(this DateTime targetTime, string timeZoneId)
{
var timezone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
return TimeZoneInfo.ConvertTimeToUtc(targetTime, timezone);
}
`
Thanks to everyone who helped with this question