Converts an existing to a but normalizes the so that comparisons of converted instances retain the UTC local agnostic behavior. - CSharp System

CSharp examples for System:DateTime UTC

Description

Converts an existing to a but normalizes the so that comparisons of converted instances retain the UTC local agnostic behavior.

Demo Code


using System;/*from  w w  w.  ja  v  a 2s.  c  o m*/

public class Main{
        /// <summary>
        /// Converts an existing <see cref="DateTime"/> to a <see cref="DateTimeOffset"/> but normalizes the <see cref="DateTimeKind"/> 
        /// so that comparisons of converted <see cref="DateTime"/> instances retain the UTC/local agnostic behavior.
        /// </summary>
        public static DateTimeOffset ToDateTimeOffset(this DateTime dateTime)
        {
            try
            {
                return DateTime.SpecifyKind(dateTime, DateTimeKind.Local);
            }
            catch (ArgumentOutOfRangeException)
            {
                return new DateTimeOffset(DateTime.SpecifyKind(dateTime, DateTimeKind.Utc), TimeSpan.Zero);
            }
        }
}

Related Tutorials