@manhnguyenv

Welcome to my blog!

Using DateTime in CSharp

November 27, 2018 01:18

Snippet - Using DateTime in CSharp (edit)

using System;
 
namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            //
            // https://docs.microsoft.com/en-us/dotnet/standard/datetime/converting-between-time-zones
            //
 
            var dt = DateTime.UtcNow;
            Console.WriteLine(dt);
 
            //
            // https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
            //
            DateTime dateNow = DateTime.Now;
            Console.WriteLine(TimeZoneInfo.ConvertTimeToUtc(dateNow));
 
            //
            // https://blog.submain.com/4-common-datetime-mistakes-c-avoid/
            //
            TimeZoneInfo tz = TimeZoneInfo.Local; // getting the current system timezone
 
            string s = "11/26/2018 6:17:40 PM";
            DateTime dateTime = GetDateTimeFromUserInput(s); // or another external untrusted source
 
            if (tz.IsAmbiguousTime(dateTime))
            {
                // do something
            }
 
            if (tz.IsInvalidTime(dateTime))
            {
                // do something
            }
 
            Console.WriteLine("OK");
        }
 
        private static DateTime GetDateTimeFromUserInput(string s)
        {
            return Convert.ToDateTime(s);
        }
    }
}

Categories

Recent posts