Many times we store Dates in our database by passing DateTime as a parameter value or by using GETDATE() in SQL Server. In both the cases, the time of the current machine is passed as the value. It is OK in case of Desktop applications however, when we move to web applications, the current computer is the server where the website/app is hosted. This means if you’re in India and the website is hosted in a server in the US, the time stored in the database will be US time and not your local time. The correct way is to store the time in the local timezone. In this post we will see how to convert a DateTime object into specific TimeZone in C#.
To do this, we will use the FindSystemTimeZoneById() of TimeZoneInfo class. This function takes Id as a parameter to return the equivalent time in timezone passed. In the example below, we are taking the current system time and converting it into “Central Standard Time”.
- DateTime currentTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
Let me know via comments if you are aware of about other ways to perform this action.