Sponsored Ad

Friday, May 18, 2012

Convert Local Date and Time to IST/EST/CST Time Zones in C#

Time Zones are very important when you are developing a international application. You have to show the date and time for that country. The below program is an example to convert the local datetime into IST/EST/CST.

To get local Date and Time use DateTime.Now, it will return the current date and time.

DateTime CurrentLocalTime = DateTime.Now;

To convert local datetime into specific timezone use TimeZoneInfo.ConvertTime() method and pass the local time and the time in which you want to convert it.

For example to convert local time into “US Mountain Standard Time”, use the following line.

DateTime USALocal = TimeZoneInfo.ConvertTime(CurrentLocalTime, TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time"));

Similarly if you want to convert local time to “Eastern Standard Time” use the following line:

DateTime ESTTime = TimeZoneInfo.ConvertTime(CurrentLocalTime, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));

The full program is given below and the output is also available. Please let me know if you have any questions while implementing this.


Convert Local Date and Time to IST/EST/CST Time Zones in C#

Source Code for TimeZone Conversion:

using System;

namespace CSharpTalk
{
    class Programs
    {
        static void Main(string[] args)
        {

            DateTime CurrentLocalTime = DateTime.Now;

            Console.WriteLine("Your Local Time: {0}", CurrentLocalTime);
            DateTime USALocal = TimeZoneInfo.ConvertTime(CurrentLocalTime, TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time"));
            Console.WriteLine("USA Standard Time (US Mountain Standard Time): {0}", USALocal);

            DateTime ESTTime = TimeZoneInfo.ConvertTime(CurrentLocalTime, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
            Console.WriteLine("Eastern Standard Time (EST): {0}", ESTTime);

            DateTime ISTTime = TimeZoneInfo.ConvertTime(CurrentLocalTime, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
            Console.WriteLine("India Standard Time (IST): {0}", ISTTime);

            DateTime CanadaTime = TimeZoneInfo.ConvertTime(CurrentLocalTime, TimeZoneInfo.FindSystemTimeZoneById("Canada Central Standard Time"));
            Console.WriteLine("Canada Central Standard Time : {0}", CanadaTime);

            Console.ReadLine();
        }

    }
}

No comments:

Post a Comment

Sponsored Ad

Website Update

Followers