How to Convert Time in Different Time Zones C#

Time Zone
In this article, we will discuss about how to convert time according to time zone. I am using TuneZoneInfo class to retrieve information about the current time zone and you can convert it to UTC (Coordinated Universal Time) or vice versa. And also you can use this class to retrieve information on any time zone defined on the local system.




#region TimeZoneConverter Source 

      private void frmTimeZoneConverter_Load(object sender, EventArgs e)
      {
         // get and set current date and time
         lblLocalTimeIndicator.Text = DateTime.Now.ToString();

         // Get system (local) time zone information in to readonlycollection list
         ReadOnlyCollection<TimeZoneInfo> TimeZoneColl = TimeZoneInfo.GetSystemTimeZones();
         cmbTimeZones.DataSource = TimeZoneColl;
         cmbTimeZones.DisplayMember = "DisplayName";
         cmbTimeZones.ValueMember = "Id";

      }

      private void cmdTimeConvert_Click(object sender, EventArgs e)
      {
         if (cmbTimeZones.SelectedIndex > 0)
         {
            DateTime dt = DateTime.Now;

            // Convert current time in to selected time zone.
            lblConvertedTime.Text = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt, TimeZoneInfo.Local.Id, cmbTimeZones.SelectedValue.ToString()).ToString();

         }
      }

      #endregion TimeZoneConverter

      #region Information 
      private void GenaralInformation()
      {
         TimeZoneInfo tzi = TimeZoneInfo.Local;

         // Gets and sets standared time zone name.
         lblCurrentTimeZoneStd.Text = tzi.StandardName;

         // Gets and sets the daylight saving time zone name.
         lblCurrentTimeZoneDlt.Text = tzi.DaylightName;

         //set current time and date
         lblCurrTime.Text = DateTime.Now.ToString();

         // check whether daylight serving is available
         lblDaylightSavingYes.Text = tzi.IsDaylightSavingTime(DateTime.Now).ToString();

         // set universal time
         lblUniTime.Text = DateTime.Now.ToUniversalTime().ToString();

         // get and set time different between local and universal time(UTC).
         lblOffset.Text = tzi.BaseUtcOffset.ToString();

      }

      private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
      {
         GenaralInformation();
      }

      #endregion





This will Support this .Net frameworks
.net framework 4.0
.net framework 3.5
.net framework 3.0
.net framework 2.0

.NET Framework Client Profiles
Supported in: 4, 3.5 SP1

The entire source code of this article can be downloaded over here.

If you have any question regarding this article please be kind enough to mention it on comment area.
Thank you for viewing this article.
Give me a +1 if you think it was a good article


0 comments:

Post a Comment

Thank you very much