SUN SUN - 1 month ago 7
ASP.NET (C#) Question

Display welcome message as per local time in asp.net

I have below code which shows Wishing message to user as per their current local time. This works fine in my localhost but in after uploading it to server it shows server time. How do I convert it to IST?

private void admin_Default2_Load(object sender, EventArgs e)
{
if (DateTime.Now.Hour < 12) {
lblGreeting.Text = "Good Morning";
lblDate.Text = Convert.ToString(DateTime.Now);
} else if (DateTime.Now.Hour < 17) {
lblGreeting.Text = "Good Afternoon";
lblDate.Text = Convert.ToString(DateTime.Now);
} else {
lblGreeting.Text = "Good Evening";
lblDate.Text = Convert.ToString(DateTime.Now);
}
}

Answer

Just convert your current time in to UTC & add 5.5 hours if you want IST

if (DateTime.UtcNow.AddHours(5.5).Hour < 12) {
    lblGreeting.Text = "Good Morning";
    lblDate.Text = Convert.ToString(DateTime.UtcNow.AddHours(5.5));
} else if (DateTime.UtcNow.AddHours(5.5).Hour < 17) {
    lblGreeting.Text = "Good Afternoon";
    lblDate.Text = Convert.ToString(DateTime.UtcNow.AddHours(5.5));
} else {
    lblGreeting.Text = "Good Evening";
    lblDate.Text = Convert.ToString(DateTime.UtcNow.AddHours(5.5));
}