William's profile.Net ZoneBlogLists Tools Help

Blog


    August 31

    Convert local time to Timezone.

    I think Live Writer will get me bloggin again.  Anyway, here is a class that allows you to convert a DateTime to any Timezone.  You can convert between local timezones and to/from UTC. It leverages Windows apis to do the conversion and uses the internal timezone structures.

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Collections;
    using System.Runtime.InteropServices;
    using Microsoft.Win32;

    namespace WJS.Utils
    {
    /// <summary>
    /// Date: 12/4/2005
    /// Created By: William Stacey, MVP
    /// Used to convert to/from utc times and local times and respect DST.
    /// Can also covert between two local time zones.
    /// Information about a time zone containing methods to convert local times to and from UTC and
    /// between local time zones.
    /// </summary>
    [Serializable]
    public class TimeZoneInformation
    {
    #region Fields
    private TZI tzi; // Current time zone information.
    private string displayName; // Current time zone display name.
    private string standardName; // Current time zone standard name (non-DST).
    private string daylightName; // Current time zone daylight name (DST).
    private static readonly List<TimeZoneInformation> timeZones; // static list of all time zones on machine.
    #endregion

    #region Constructors
    private TimeZoneInformation()
    {
    }

    static TimeZoneInformation()
    {
    timeZones = new List<TimeZoneInformation>();

    using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"))
    {
    string[] zoneNames = key.GetSubKeyNames();

    foreach (string zoneName in zoneNames)
    {
    using (RegistryKey subKey = key.OpenSubKey(zoneName))
    {
    TimeZoneInformation tzi = new TimeZoneInformation();
    tzi.displayName = (string)subKey.GetValue("Display");
    tzi.standardName = (string)subKey.GetValue("Std");
    tzi.daylightName = (string)subKey.GetValue("Dlt");
    tzi.InitTzi((byte[])subKey.GetValue("Tzi"));
    timeZones.Add(tzi);
    }
    }
    }
    }
    #endregion

    #region Public Properties
    /// <summary>
    /// Gets list of all time zones defined on the current computer system.
    /// </summary>
    public static List<TimeZoneInformation> TimeZones
    {
    get
    {
    // Return a copy of the list.
    List<TimeZoneInformation> nList = new List<TimeZoneInformation>(timeZones);
    return nList;
    }
    }
    /// <summary>
    /// Gets an string array of standard time zone names supported on the current system.
    /// </summary>
    public static string[] TimeZoneNames
    {
    get
    {
    List<String> list = new List<String>();
    foreach (TimeZoneInformation tzi in timeZones)
    {
    list.Add(tzi.StandardName);
    }
    return list.ToArray();
    }
    }

    /// <summary>
    /// Gets the time zone information of the current computer system.
    /// </summary>
    public static TimeZoneInformation CurrentTimeZone
    {
    get
    {
    string tzn = TimeZone.CurrentTimeZone.StandardName;
    TimeZoneInformation tzi = TimeZoneInformation.GetTimeZone(tzn);
    return tzi;
    }
    }

    /// <summary>
    /// The time zone's name during 'standard' time (i.e. not daylight savings).
    /// </summary>
    public string StandardName
    {
    get
    {
    return standardName;
    }
    }

    /// <summary>
    /// The time zone's name during daylight savings time (DST).
    /// </summary>
    public string DaylightName
    {
    get
    {
    return daylightName;
    }
    }

    /// <summary>
    /// The time zone's display name (e.g. "(GMT-05:00) Eastern Time (US and Canada)").
    /// </summary>
    public string DisplayName
    {
    get
    {
    return displayName;
    }
    }

    /// <summary>
    /// Gets the standard offset from UTC as a TimeSpan.
    /// </summary>
    public TimeSpan StandardOffset
    {
    get
    {
    return TimeSpan.FromMinutes(StandardBias);
    }
    }

    /// <summary>
    /// Gets the daylight offset from UTC as a TimeSpan.
    /// </summary>
    public TimeSpan DaylightOffset
    {
    get
    {
    return TimeSpan.FromMinutes(DaylightBias);
    }
    }

    /// <summary>
    /// Gets the difference, in minutes, between UTC and local time.
    /// UTC = local time + bias.
    /// </summary>
    public int StandardBias
    {
    get
    {
    return -(tzi.bias + tzi.standardBias);
    }
    }

    /// <summary>
    /// Gets the difference, in minutes, between UTC and local time (in daylight savings time).
    /// UTC = local time + bias.
    /// </summary>
    public int DaylightBias
    {
    get
    {
    return -(tzi.bias + tzi.daylightBias);
    }
    }

    #endregion

    #region Public Methods

    /// <summary>
    /// Returns standard name of this time zone instance.
    /// </summary>
    /// <returns>Time zone standard name.</returns>
    public override string ToString()
    {
    return this.standardName;
    }

    /// <summary>
    /// Returns a TimeZoneInformation instance for the time zone with supplied standard name.
    /// </summary>
    /// <param name="standardTimeZoneName">Standard name of the time zone.</param>
    /// <returns>TimeZoneInformation instance.</returns>
    /// <exception cref="ArgumentException">Thrown if name not found.</exception>
    public static TimeZoneInformation GetTimeZone(string standardTimeZoneName)
    {
    if (standardTimeZoneName == null)
    standardTimeZoneName = "."
    if (standardTimeZoneName == ".")
    standardTimeZoneName = TimeZone.CurrentTimeZone.StandardName;

    foreach (TimeZoneInformation tzi in TimeZoneInformation.TimeZones)
    {
    if (tzi.StandardName.Equals(standardTimeZoneName, StringComparison.OrdinalIgnoreCase))
    return tzi;
    }
    throw new ArgumentException("standardTimeZoneName not found.");
    }

    /// <summary>
    /// Converts the value of the utc time to a local time in this time zone.
    /// </summary>
    /// <param name="utc">The UTC time to convert.</param>
    /// <returns>The local time.</returns>
    public DateTime ToLocalTime(DateTime utc)
    {
    // Convert to SYSTEMTIME
    SYSTEMTIME stUTC = DateTimeToSystemTime(utc);

    // Set up the TIME_ZONE_INFORMATION
    TIME_ZONE_INFORMATION tziNative = TziNative();
    SYSTEMTIME stLocal;
    NativeMethods.SystemTimeToTzSpecificLocalTime(ref tziNative, ref stUTC, out stLocal);

    // Convert back to DateTime
    return SystemTimeToDateTime(ref stLocal);
    }

    /// <summary>
    /// Converts the value of the utc time to local time in supplied time zone.
    /// </summary>
    /// <param name="utc">The time to convert.</param>
    /// <param name="targetTimeZoneName">The standard name of the time zone.</param>
    /// <returns>The local time.</returns>
    /// <exception cref="ArgumentException">Thrown if time zone not found.</exception>
    public static DateTime ToLocalTime(DateTime utc, string targetTimeZoneName)
    {
    TimeZoneInformation tzi = TimeZoneInformation.GetTimeZone(targetTimeZoneName);
    return tzi.ToLocalTime(utc);
    }

    /// <summary>
    /// Converts a localTime from a source time zone to a target time zone, adjusting for DST as needed.
    /// The localTime must be a local time in the sourceTimeZoneName time zone.
    /// </summary>
    /// <param name="sourceTimeZoneName">Time zone name which represents localTime.</param>
    /// <param name="localTime">The source local time.</param>
    /// <param name="targetTimeZoneName">The time zone name which to convert the localTime.</param>
    /// <returns>The local time for targetTimeZoneName.</returns>
    public static DateTime ToLocalTime(string sourceTimeZoneName, DateTime localTime, string targetTimeZoneName)
    {
    DateTime utc = TimeZoneInformation.ToUniversalTime(sourceTimeZoneName, localTime);
    DateTime lt = TimeZoneInformation.ToLocalTime(utc, targetTimeZoneName);
    return lt;
    }

    /// <summary>
    /// Converts the value of the local time to UTC time.
    /// Note that there may be different possible interpretations at the daylight time boundaries.
    /// </summary>
    /// <param name="local">The local time to convert.</param>
    /// <returns>The UTC DateTime.</returns>
    /// <exception cref="NotSupportedException">Thrown if the method failed due to missing platform support.</exception>
    public DateTime ToUniversalTime(DateTime local)
    {
    SYSTEMTIME stLocal = DateTimeToSystemTime(local);
    TIME_ZONE_INFORMATION tziNative = TziNative();
    SYSTEMTIME stUTC;

    try
    {
    NativeMethods.TzSpecificLocalTimeToSystemTime(ref tziNative, ref stLocal, out stUTC);
    return SystemTimeToDateTime(ref stUTC);
    }
    catch (EntryPointNotFoundException e)
    {
    throw new NotSupportedException("This method is not supported on this operating system", e);
    }
    }

    /// <summary>
    /// Converts a local time in specified time zone to UTC time.
    /// </summary>
    /// <param name="standardTimeZoneName">The standard time zone name.</param>
    /// <param name="local">The local time to convert.</param>
    /// <returns>The UTC time.</returns>
    /// <exception cref="ArgumentException">Thrown if time zone name not found.</exception>
    /// <exception cref="NotSupportedException">Thrown if the method failed due to missing platform support.</exception>
    public static DateTime ToUniversalTime(string standardTimeZoneName, DateTime local)
    {
    TimeZoneInformation tzi = TimeZoneInformation.GetTimeZone(standardTimeZoneName);
    return tzi.ToUniversalTime(local);
    }
    #endregion

    #region Private Methods
    private static SYSTEMTIME DateTimeToSystemTime(DateTime dt)
    {
    SYSTEMTIME st;
    FILETIME ft = new FILETIME();
    ft.dwHighDateTime = (int)(dt.Ticks >> 32);
    ft.dwLowDateTime = (int)(dt.Ticks & 0xFFFFFFFFL);
    NativeMethods.FileTimeToSystemTime(ref ft, out st);
    return st;
    }

    private static DateTime SystemTimeToDateTime(ref SYSTEMTIME st)
    {
    FILETIME ft = new FILETIME();
    NativeMethods.SystemTimeToFileTime(ref st, out ft);
    DateTime dt = new DateTime((((long)ft.dwHighDateTime) << 32) | (uint)ft.dwLowDateTime);
    return dt;
    }

    private TIME_ZONE_INFORMATION TziNative()
    {
    TIME_ZONE_INFORMATION tziNative = new TIME_ZONE_INFORMATION();
    tziNative.Bias = tzi.bias;
    tziNative.StandardDate = tzi.standardDate;
    tziNative.StandardBias = tzi.standardBias;
    tziNative.DaylightDate = tzi.daylightDate;
    tziNative.DaylightBias = tzi.daylightBias;
    return tziNative;
    }

    /// <summary>
    /// The standard Windows SYSTEMTIME structure.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    private struct SYSTEMTIME
    {
    public UInt16 wYear;
    public UInt16 wMonth;
    public UInt16 wDayOfWeek;
    public UInt16 wDay;
    public UInt16 wHour;
    public UInt16 wMinute;
    public UInt16 wSecond;
    public UInt16 wMilliseconds;
    }

    // FILETIME is already declared in System.Runtime.InteropServices.

    /// <summary>
    /// The layout of the Tzi value in the registry.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    private struct TZI
    {
    public int bias;
    public int standardBias;
    public int daylightBias;
    public SYSTEMTIME standardDate;
    public SYSTEMTIME daylightDate;
    }

    /// <summary>
    /// The standard Win32 TIME_ZONE_INFORMATION structure.
    /// Thanks to www.pinvoke.net.
    /// </summary>
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    private struct TIME_ZONE_INFORMATION
    {
    [MarshalAs(UnmanagedType.I4)]
    public Int32 Bias;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    public string StandardName;
    public SYSTEMTIME StandardDate;
    [MarshalAs(UnmanagedType.I4)]
    public Int32 StandardBias;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    public string DaylightName;
    public SYSTEMTIME DaylightDate;
    [MarshalAs(UnmanagedType.I4)]
    public Int32 DaylightBias;
    }

    /// <summary>
    /// A container for P/Invoke declarations.
    /// </summary>
    private struct NativeMethods
    {
    private const string KERNEL32 = "kernel32.dll"

    [DllImport(KERNEL32)]
    public static extern uint GetTimeZoneInformation(out TIME_ZONE_INFORMATION
    lpTimeZoneInformation);

    [DllImport(KERNEL32)]
    public static extern bool SystemTimeToTzSpecificLocalTime(
    [In] ref TIME_ZONE_INFORMATION lpTimeZone,
    [In] ref SYSTEMTIME lpUniversalTime,
    out SYSTEMTIME lpLocalTime);

    [DllImport(KERNEL32)]
    public static extern bool SystemTimeToFileTime(
    [In] ref SYSTEMTIME lpSystemTime,
    out FILETIME lpFileTime);

    [DllImport(KERNEL32)]
    public static extern bool FileTimeToSystemTime(
    [In] ref FILETIME lpFileTime,
    out SYSTEMTIME lpSystemTime);

    /// <summary>
    /// Convert a local time to UTC, using the supplied time zone information.
    /// Windows XP and Server 2003 and later only.
    /// </summary>
    /// <param name="lpTimeZone">The time zone to use.</param>
    /// <param name="lpLocalTime">The local time to convert.</param>
    /// <param name="lpUniversalTime">The resultant time in UTC.</param>
    /// <returns>true if successful, false otherwise.</returns>
    [DllImport(KERNEL32)]
    public static extern bool TzSpecificLocalTimeToSystemTime(
    [In] ref TIME_ZONE_INFORMATION lpTimeZone,
    [In] ref SYSTEMTIME lpLocalTime,
    out SYSTEMTIME lpUniversalTime);
    }

    /// <summary>
    /// Initialise the m_tzi member.
    /// </summary>
    /// <param name="info">The Tzi data from the registry.</param>
    private void InitTzi(byte[] info)
    {
    if (info.Length != Marshal.SizeOf(tzi))
    throw new ArgumentException("Information size is incorrect", "info");

    // Could have sworn there's a Marshal operation to pack bytes into
    // a structure, but I can't see it. Do it manually.
    GCHandle h = GCHandle.Alloc(info, GCHandleType.Pinned);
    try
    {
    tzi = (TZI)Marshal.PtrToStructure(h.AddrOfPinnedObject(), typeof(TZI));
    }
    finally
    {
    h.Free();
    }
    }
    #endregion
    }
    }

    Comments (88)

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    No namewrote:
    http://www.batteryfast.com/dell/latitude-x1.htm dell latitude x1 battery,
    http://www.batteryfast.com/dell/xd187.htm dell xd187 battery,
    http://www.batteryfast.com/dell/inspiron-1300.htm dell inspiron 1300 battery,
    http://www.batteryfast.com/dell/inspiron-b120.htm dell inspiron b120 battery,
    http://www.batteryfast.com/dell/inspiron-b130.htm dell inspiron b130 battery,
    http://www.batteryfast.com/gateway/m680.htm gateway m680 battery,
    http://www.batteryfast.com/gateway/m360.htm gateway m360 battery,
    http://www.batteryfast.com/gateway/m460.htm gateway m460 battery,
    http://www.batteryfast.com/hp/m2000.htm hp m2000 battery,
    http://www.batteryfast.com/hp/dv1000.htm hp dv1000 battery,
    http://www.batteryfast.com/hp/dv4000.htm hp dv4000 battery,
    http://www.batteryfast.com/hp/ze2000.htm hp ze2000 battery,
    http://www.batteryfast.com/hp/hstnn-db17.htm hp hstnn-db17 battery,
    http://www.batteryfast.com/hp/n6000.htm hp n6000 battery,
    http://www.batteryfast.com/hp/n6100.htm hp n6100 battery,
    http://www.batteryfast.com/hp/f2019.htm hp f2019 battery,
    http://www.batteryfast.com/hp/f2019a.htm hp f2019a battery,
    http://www.batteryfast.com/hp/f2019b.htm hp f2019b battery,
    http://www.batteryfast.com/hp/hstnn-db02.htm hp hstnn-db02 battery,
    http://www.batteryfast.com/hp/dp399a.htm hp dp399a battery,
    http://www.batteryfast.com/hp/383968-001.htm hp 383968-001 battery,
    http://www.batteryfast.com/hp/f1739a.htm hp f1739a battery,
    http://www.batteryfast.com/hp/n3000.htm hp n3000 battery,
    http://www.batteryfast.com/hp/n3490.htm hp n3490 battery,
    http://www.batteryfast.com/hp/zt1000.htm hp zt1000 battery,
    http://www.batteryfast.com/hp/f2299a.htm hp f2299a battery,
    http://www.batteryfast.com/hp/f3172b.htm hp f3172b battery,
    http://www.batteryfast.com/hp/f3172a.htm hp f3172a battery,
    http://www.batteryfast.com/gateway/m500.htm gateway m500 battery,
    http://www.batteryfast.com/toshiba/pa3382u-1bas.htm toshiba pa3382u-1bas battery,
    http://www.batteryfast.com/toshiba/pa3382u-1brs.htm toshiba pa3382u-1brs battery,
    http://www.batteryfast.com/toshiba/pa3384u-1bas.htm toshiba pa3384u-1bas battery,
    http://www.batteryfast.com/toshiba/pa3395u-1brs.htm toshiba pa3395u-1brs battery,
    http://www.batteryfast.com/toshiba/pa3421u-1brs.htm toshiba pa3421u-1brs battery,
    http://www.batteryfast.com/toshiba/pa3465u-1brs.htm toshiba pa3465u-1brs battery,
    http://www.batteryfast.com/toshiba/pabas069.htm toshiba pabas069 battery,
    http://www.batteryfast.com/gateway/6500358.htm gateway 6500358 battery,
    http://www.batteryfast.com/gateway/gt-6300l.htm gateway gt-6300l battery,
    http://www.batteryfast.com/gateway/solo-9300.htm gateway solo 9300 battery,
    http://www.batteryfast.com/acer/aspire-1200.htm acer aspire 1200 battery,
    http://www.batteryfast.com/acer/aspire-1600.htm acer aspire 1600 battery,
    http://www.batteryfast.com/acer/btp-44a3.htm acer btp-44a3 battery,
    http://www.batteryfast.com/acer/btp-25d1.htm acer btp-25d1 battery,
    http://www.batteryfast.com/acer/travelmate-330.htm acer travelmate 330 battery,
    http://www.batteryfast.com/acer/travelmate-330t.htm acer travelmate 330t battery,
    http://www.batteryfast.com/acer/batefl50l6c40.htm acer batefl50l6c40 battery,
    http://www.batteryfast.com/acer/batefl50l6c48.htm acer batefl50l6c48 battery,
    http://www.batteryfast.com/acer/travelmate-2400.htm acer travelmate 2400 battery,
    http://www.batteryfast.com/acer/aspire-5500.htm acer aspire 5500 battery,
    http://www.batteryfast.com/acer/aspire-5600.htm acer aspire 5600 battery,
    http://www.batteryfast.com/acer/batefl50l6c48.htm acer batefl50l6c48 battery,
    Dec. 11
    Picture of Anonymous
    Nov. 21
    Picture of Anonymous
    Nov. 21
    Nov. 4
    Nov. 1
    Oct. 30
    No namewrote:

    Hi,Do you need digital signages, advertising displays, digital sign, advertisement displays and advertising players? Please go Here:www.amberdigital.com.hk(Amberdigital).we have explored and developed the international market with professionalism. We have built a widespread marketing network, and set up a capable management team dedicated to provide beyond-expectation services to our customers.

    amberdigital Contact Us

    website:www.amberdigital.com.hk
    alibaba:amberdigital.en.alibaba.com[cibgacdficiijab]

    Oct. 26
    Oct. 20
    No namewrote:
    東京/大阪のクリエイター育成専門の学校 バンタンデザイン研究所。大阪 専門学校ファッションや美容の専門の学校です. 大阪 専門学校デザインスクール最大級の超複合型イベント
    Oct. 7
    Oct. 7
    Oct. 7
    No namewrote:

    横浜デリヘル 横浜横浜のホームページへようこそ。横浜、川崎、藤沢、横須賀、鎌倉、逗子、大和横浜デリヘル致します。当店は無店舗型風俗店(出張風俗・デリヘル横浜デリヘル風俗)です

    Sept. 30
    No namewrote:
    勃起薬勃起不全, 勃起薬,勃起, 勃起 不全勃起機能低下, インポ,勃起薬,勃起薬,M勃起薬AX,マッ勃起薬
    Sept. 30
    No namewrote:
    男性下着のことならプロパガンダ。他にも男性下着、ビキニ、マ男性下着、トランクスからセクシー系まで。男性下着のことならお任せください。"
    Sept. 30
    No namewrote:
    吉原 ソープ今までの吉原にはまったくない、新しい吉原 ソープのお店です。お客様に提供するのは、究極の癒しと吉原 ソープです。今まで吉原 ソープに縁の無かったお客様のニーズにお応えします。
    Sept. 30
    No namewrote:
    18歳以上の方デリヘル店の最新デリヘル情報満載です。 高級出張 デリヘル情報 デリヘル嬢等、地域別に検索できます
    Sept. 30
    No namewrote:

    品川デリヘル高級デリヘル, 品川デリヘル品川の品川デリヘル店「品川デリヘル東京」では高級感ある品川デリヘル極上なひとときをご提供します

    Sept. 30
    No namewrote:
    幸せな結婚のためには結婚式をしたほうがいいの? 【結婚パレット】は既婚者もたくさん参加する「結婚準備の情報コミュニティ」。だから結婚準備に関するどんなお悩みでもきっと良い答えが見つかるはず。恋愛,婚約,入籍,結婚, 結婚式場,披露宴,格安,格安挙式,結婚費用妻も「お金あまり無いから結婚式はいいよ」と言っていたので、籍だけ入れて、早一年。妻と都内に買い物に出た時、俺は見てしまった・・・。ウィンドウ越しに少し寂しそうにウェディングトレスを見つめる妻の姿を!「結婚式挙げたいの?」と聞くと、恥ずかしそうに「うん・・・まあね・・・」と答える妻。なんか、その時きたんですよね。くぅ~ってものが!その瞬間決めましたね、結婚式
    Sept. 30
    No namewrote:
    外国為替取引はじめるなら、新東京シティ証券の『為替マーケット』。最新FX情報を手に入れてリスクの少ないFX取引!仮想トレードでの外国為替無料体験も。FX,外国為替,FX取引,外国為替証拠金取引,外為外国為替取引)はじめるなら、為替マーケット。の新東京シティ証券
    Sept. 30
    No namewrote:

    利用料完全無料の出会い系  サイト。男性も女性も出会いたい人はセンターに決まり。安全対策も万全。出会い系  サイトトラブル対処法! 大人なら引っかかりたくない出会い系サイトのトラブル対処法を紹介します。大人の出会い系  サイト。出会い系サイトのトラブル対処法い希望者が集まるサイト。エッチなユーザー多数なので気軽な出会いを求めている人にオススメ。

    Sept. 30

    Trackbacks

    Weblogs that reference this entry
    • None