Convert from a W3C (http:www.w3.org-datetime) to a .NET DateTime (based in local timezone) - CSharp System

CSharp examples for System:DateTime Timezone

Description

Convert from a W3C (http:www.w3.org-datetime) to a .NET DateTime (based in local timezone)

Demo Code

// Copyright (c) .NET Foundation. All rights reserved.
using System.Windows.Forms;
using OpenLiveWriter.Interop.Windows;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Diagnostics;
using System;/*from   www. ja va2  s. co m*/

public class Main{
        /// <summary>
        /// Convert from a W3C (http://www.w3.org/TR/NOTE-datetime) to a .NET DateTime (based in local timezone)
        /// </summary>
        /// <param name="w3cDateTime">w3c date-time</param>
        /// <returns></returns>
        public static DateTime ToDateTime(string w3cDateTime)
        {
            IFormatProvider culture = new CultureInfo("en-US", true);
            DateTime dateTime;
            try
            {
                dateTime = DateTime.ParseExact(w3cDateTime, W3C_DATE_FORMATS, culture, DateTimeStyles.AllowWhiteSpaces);
            }
            catch (Exception)
            {
                //Now try the W3C UTC date formats
                //Since .NET doesn't realize the the 'Z' is an indicator of the GMT timezone,
                //ParseExact will return the date exactly as parsed (no shift for GMT) so we have
                //to call ToLocalTime() on it to get it into the local time zone.
                dateTime = DateTime.ParseExact(w3cDateTime, W3C_DATE_FORMATS_UTC, culture, DateTimeStyles.AllowWhiteSpaces);
                dateTime = LocalToUtc(dateTime);
            }
            return dateTime;
        }
        /// <summary>
        /// Converts local FILETIME to local DateTime,
        /// or UTC FILETIME to UTC DateTime.
        /// </summary>
        public static DateTime ToDateTime(System.Runtime.InteropServices.ComTypes.FILETIME fileTime)
        {
            long ticks = BASETICKS + ((fileTime.dwLowDateTime & 0xFFFFFFFF) | ((long)fileTime.dwHighDateTime << 32));
            return new DateTime(Math.Min(Math.Max(DateTime.MinValue.Ticks, ticks), DateTime.MaxValue.Ticks));
        }
}

Related Tutorials