Convert DateTime to Local with TimeZone using C# and VB.Net in ASP.Net

Last Reply one month ago By dharmendr

Posted one month ago

Dear All,

I have done an application which runs on C# and Asp.net. The application does hotel room booking send cancelation details. But I am having an issue in UTC time.

Example: Hotel in Sri Lanka and client in the USA. But application runs on Singapore server. These three countries time difference I am unable to send email exact date. email sending server in UTC time +8:00 and Hotel in UTC +5:30 and client in UTC -6:00.


Posted one month ago

Hi Thilan,

First get the server timezone.

Then get the client timezone using JavaScript.

Then using ConvertTime method of TimeZoneInfo, convert time to local time.

for more details refer below link.

https://docs.microsoft.com/en-us/dotnet/standard/datetime/converting-between-time-zones

HTML

<script type="text/javascript">
    window.onload = function () {
        var date = new Date();
        var tzstr = date.toTimeString().split("(");
        var timezone = tzstr[1].toString().replace(")", "");
        document.getElementById('hfTimezone').value = timezone;
    };
</script>
<asp:HiddenField ID="hfTimezone" runat="server" />
<asp:Button Text="Get" runat="server" OnClick="GetLocal" />

C#

protected void GetLocal(object sender, EventArgs e)
{
    // 21-Aug-2019 11:59:59 AM
    DateTime time = ConvertDateTimeToLocal(new DateTime(2019, 08, 21, 11, 59, 59));
}

protected DateTime ConvertDateTimeToLocal(DateTime dateTime)
{
    TimeZoneInfo serverTimeZone = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id); // Get Server TimeZone
    TimeZoneInfo clientTimeZone = TimeZoneInfo.FindSystemTimeZoneById(hfTimezone.Value); // Get client TimeZone
    DateTime localTime = TimeZoneInfo.ConvertTime(dateTime, serverTimeZone, clientTimeZone); // Convert to local time
    return localTime;
}

VB.Net

Protected Sub GetLocal(ByVal sender As Object, ByVal e As EventArgs)
    ' 21-Aug-2019 11:59:59 AM
    Dim time As DateTime = ConvertDateTimeToLocal(New DateTime(2019, 8, 21, 11, 59, 59))
End Sub

Protected Function ConvertDateTimeToLocal(ByVal dateTime As DateTime) As DateTime
    Dim serverTimeZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id) 'Get Server TimeZone
    Dim clientTimeZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(hfTimezone.Value) ' Get client TimeZone
    Dim localTime As DateTime = TimeZoneInfo.ConvertTime(dateTime, serverTimeZone, clientTimeZone) ' Convert to local time
    Return localTime
End Function

Here i am saving the client TimeZone in HiddenField on load.