DateTime

  1. แสดงปีเป็น พ.ศ. และ ค.ศ. ด้วย CultureInfo()
  2. การแปลง string เป็น DateTime โดยใช้ ParseExact()
  3. การเพิ่ม-ลด วัน เดือน ปี
  4. การหาจำนวนวันระหว่าง 2 DateTime
  5. การ for loop วัน – เวลา
  6. แสดงวันที่จาก DateTime แบบต่างๆ
  7. ตรวจสอบวันที่ ถ้า T1 น้อยกว่า T2 ให้ Error
  8. ตรวจสอบว่า DateTime? เป็น null หรือไม่
  9. DateTime.TryParseExact()

DateTime Struct

1.แสดงปีเป็น พ.ศ. และ ค.ศ. ด้วย CultureInfo()

new CultureInfo("en-US") จะได้ปีเป็น ค.ศ.
new CultureInfo("th-TH") จะได้ปีเป็น พ.ศ.

using System;
using System.Globalization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(DateTime.Today.ToString("dd/MM/yyyy", new CultureInfo("en-US")));
            Console.WriteLine(DateTime.Today.ToString("dd/MM/yyyy", new CultureInfo("th-TH")));
            Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss", new CultureInfo("en-US")));
            Console.WriteLine(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss", new CultureInfo("th-TH")));
        }
    }
}

ผลการรัน

25/03/2019
25/03/2562
25/03/2019 10:22:48
25/03/2562 10:22:48

2.การแปลง string เป็น DateTime โดยใช้ ParseExact()

using System;
using System.Globalization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string stDate1 = "31/01/2019";
            DateTime date1 = DateTime.ParseExact(stDate1, "d/M/yyyy", new CultureInfo("en-US"));
            Console.WriteLine(date1.ToString("yyyy-MM-dd", new CultureInfo("en-US")));

            string stDate2 = "20190228";
            DateTime date2 = DateTime.ParseExact(stDate2, "yyyyMMdd", new CultureInfo("en-US"));
            Console.WriteLine(date2.ToString("yyyy-MM-dd", new CultureInfo("en-US")));

            string stDate3 = "2019-03-25 22:12 PM";
            DateTime date3 = DateTime.ParseExact(stDate3, "yyyy-MM-dd HH:mm tt", new CultureInfo("en-US"));
            Console.WriteLine(date3.ToString("yyyy-MM-dd HH:mm tt", new CultureInfo("en-US")));
        }
    }
}

3.การเพิ่ม-ลด วัน เดือน ปี

using System;
using System.Globalization;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime d1 = new DateTime(2019, 1, 15);
            Console.WriteLine(d1.AddDays(-1).ToString("yyyy-MM-dd", new CultureInfo("en-US")));
            Console.WriteLine(d1.ToString("yyyy-MM-dd", new CultureInfo("en-US")));
            Console.WriteLine(d1.AddDays(1).ToString("yyyy-MM-dd", new CultureInfo("en-US")));
            Console.WriteLine();
            Console.WriteLine(d1.AddMonths(-1).ToString("yyyy-MM-dd", new CultureInfo("en-US")));
            Console.WriteLine(d1.ToString("yyyy-MM-dd", new CultureInfo("en-US")));
            Console.WriteLine(d1.AddMonths(1).ToString("yyyy-MM-dd", new CultureInfo("en-US")));
            Console.WriteLine();
            Console.WriteLine(d1.AddYears(-1).ToString("yyyy-MM-dd", new CultureInfo("en-US")));
            Console.WriteLine(d1.ToString("yyyy-MM-dd", new CultureInfo("en-US")));
            Console.WriteLine(d1.AddYears(1).ToString("yyyy-MM-dd", new CultureInfo("en-US")));
            Console.WriteLine();
        }
    }
}

ผลการรัน

2019-01-14
2019-01-15
2019-01-16

2018-12-15
2019-01-15
2019-02-15

2018-01-15
2019-01-15
2020-01-15

4.การหาจำนวนวันระหว่าง 2 DateTime

using System;
using System.Globalization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime d1 = DateTime.Now;
            DateTime d2 = new DateTime(2018, 10, 1);
            DateTime d3 = new DateTime(2017, 10, 1);
            Console.WriteLine("  1: " + d1.ToString());
            Console.WriteLine("  2: " + d2.ToString());
            Console.WriteLine("  3: " + d3.ToString());
            Console.WriteLine("1-2: " + (d1 - d2).ToString());
            Console.WriteLine("1-2: " + (d1 - d2).Days.ToString());
            Console.WriteLine("2-3: " + (d2 - d3).ToString());
            Console.WriteLine("2-3: " + (d2 - d3).Days.ToString());
        }
    }
}

ผลการรัน

  1: 3/25/2019 10:34:16 AM
  2: 10/1/2018 12:00:00 AM
  3: 10/1/2017 12:00:00 AM
1-2: 175.10:34:16.3605285
1-2: 175
2-3: 365.00:00:00
2-3: 365

ถ้าจะคำนวณเป็นชั่วโมงก็

using System;
using System.Globalization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime datetime1 = DateTime.ParseExact("26/03/2020 00:00:00", "d/M/yyyy HH:00:00", new CultureInfo("en-US"));
            DateTime datetime2 = DateTime.ParseExact("27/03/2020 12:00:00", "d/M/yyyy HH:00:00", new CultureInfo("en-US"));
            int diffHour = ((datetime2 - datetime1).Days * 24) + ((datetime2 - datetime1).Hours);
            Console.WriteLine(diffHour);
        }
    }
}

5.การ for loop วัน – เวลา

การ for loop วัน

using System;
using System.Globalization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime fromDate = DateTime.Today;
            DateTime toDate = DateTime.Today.AddDays(4);
            for (var day = fromDate.Date; day.Date <= toDate.Date; day = day.AddDays(1))
            {
                Console.WriteLine(day.ToString("yyyy-MM-dd", new CultureInfo("en-US")));
            }
        }
    }
}

ผลการรัน

2019-03-16
2019-03-17
2019-03-18
2019-03-19
2019-03-20

How do I loop through a date range?

การ for loop เวลา

using System;
using System.Globalization;
using System.Reflection;

namespace ConsoleApp1
{
    class Program
    {
        public static readonly log4net.ILog log = 
             log4net.LogManager.GetLogger(
             MethodBase.GetCurrentMethod().DeclaringType);

        static void Main(string[] args)
        {
            log.Info("************* BEGIN *************");
            log.Info(AppDomain.CurrentDomain.FriendlyName);

            string frTime;
            string toTime;
            DateTime initTime = DateTime.ParseExact("21/02/2020 01:00:00", "d/M/yyyy HH:mm:ss", new CultureInfo("en-US")); ;
            for (int i = 0; i < 24; i++)
            {
                frTime = initTime.AddHours(-1).ToString("dd/MM/yyyy HH:00:00", new CultureInfo("en-US"));
                toTime = initTime.ToString("dd/MM/yyyy HH:00:00", new CultureInfo("en-US"));

                log.Info(string.Format("(Round {0})", i));
                log.Info(string.Format("frTime = '{0}'", frTime));
                log.Info(string.Format("toTime = '{0}'", toTime));
                log.Info("");

                initTime = initTime.AddHours(1);
            }
        }
    }
}

6.แสดงวันที่จาก DateTime แบบต่างๆ

using System;
using System.Globalization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(DateTime.Now.ToLongDateString());
            Console.WriteLine(DateTime.Now.ToLongTimeString());
            Console.WriteLine();

            string st1 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", new CultureInfo("en-US"));
            string st2 = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss", new CultureInfo("en-US"));
            string st3 = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssK", new CultureInfo("en-US"));
            string st4 = DateTime.Now.ToString("yyyy", new CultureInfo("en-US"));
            string st5 = DateTime.Now.ToString("yyyy MMMM", new CultureInfo("en-US"));
            string st6 = DateTime.Now.ToString("yyyy MMMM", new CultureInfo("th-TH"));
            string st7 = DateTime.Now.ToString("HH:mm:ss", new CultureInfo("en-US"));
            string st8 = DateTime.Now.ToString("hh:mm:ss tt", new CultureInfo("en-US"));
            string st9 = DateTime.Now.ToString("dddd, yyyy-MM-dd HH:mm:ss", new CultureInfo("en-US"));

            Console.WriteLine(" 1: " + st1);
            Console.WriteLine(" 2: " + st2);
            Console.WriteLine(" 3: " + st3);
            Console.WriteLine(" 4: " + st4);
            Console.WriteLine(" 5: " + st5);
            Console.WriteLine(" 6: " + st6);
            Console.WriteLine(" 7: " + st7);
            Console.WriteLine(" 8: " + st8);
            Console.WriteLine(" 9: " + st9);
        }
    }
}

ผลการรัน

Monday, March 25, 2019
10:41:37 AM

 1: 2019-03-25 10:41:37
 2: 2019-03-25T10:41:37
 3: 2019-03-25T10:41:37+07:00
 4: 2019
 5: 2019 March
 6: 2562 มีนาคม
 7: 10:41:37
 8: 10:41:37 AM
 9: Monday, 2019-03-25 10:41:37

Date And Time Format In C# Programming

  1. d -> Represents the day of the month as a number from 1 through 31.
  2. dd -> Represents the day of the month as a number from 01 through 31.
  3. ddd-> Represents the abbreviated name of the day (Mon, Tues, Wed etc).
  4. dddd-> Represents the full name of the day (Monday, Tuesday etc).
  5. h 12-hour clock hour (e.g. 4).
  6. hh 12-hour clock, with a leading 0 (e.g. 06)
  7. H 24-hour clock hour (e.g. 15)
  8. HH 24-hour clock hour, with a leading 0 (e.g. 22)
  9. m Minutes
  10. mm Minutes with a leading zero
  11. M Month number(eg.3)
  12. MM Month number with leading zero(eg.04)
  13. MMM Abbreviated Month Name (e.g. Dec)
  14. MMMM Full month name (e.g. December)
  15. s Seconds
  16. ss Seconds with leading zero
  17. t Abbreviated AM / PM (e.g. A or P)
  18. tt AM / PM (e.g. AM or PM
  19. y Month Year, (e.g. 06/2019 would be June 2019)
  20. yy Year, (e.g. 2019 would be 19)
  21. yyy Year, (e.g. 2019 would be 19)
  22. yyyy Year, (e.g. 2019)
  23. K Represents the time zone information of a date and time value (e.g. +05:00)
  24. z With DateTime values, represents the signed offset of the local operating system’s time zone from Coordinated Universal Time (UTC), measured in hours. (e.g. +6)
  25. zz As z, but with leading zero (e.g. +06)
  26. zzz With DateTime values, represents the signed offset of the local operating system’s time zone from UTC,measured in hours and minutes. (e.g. +06:00)
  27. f Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value.
  28. ff Represents the two most significant digits of the seconds fraction in date and time
  29. fff Represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.
  30. ffff Represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. While it is possible to display the ten thousandths of a second component of a time value, that value may not be meaningful.
  31. fffff Represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value.
  32. ffffff Represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a Second in a date and time value.
  33. fffffff Represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value.

7.ตรวจสอบวันที่ ถ้า T1 น้อยกว่า T2 ให้ Error

using System;
using System.Globalization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string t1 = "24/09/2019";
            string t2 = DateTime.Today.ToString("dd/MM/yyyy", new CultureInfo("en-US"));

            if (isT1EarlierThanT2(t1, t2))
            {
                Console.WriteLine("Date is not valid");
            }
            else
            {
                Console.WriteLine("OK");
            }
            Console.ReadLine();
        }

        private static bool isT1EarlierThanT2(string t1, string t2)
        {
            DateTime date1 = DateTime.ParseExact(t1, "dd/MM/yyyy", new CultureInfo("en-US"));
            DateTime date2 = DateTime.ParseExact(t2, "dd/MM/yyyy", new CultureInfo("en-US"));

            int value = DateTime.Compare(date1, date2);
            if (value < 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

8.ตรวจสอบว่า DateTime? เป็น null หรือไม่

using System;
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime? dt1 = null;
            if (!dt1.HasValue)
                Console.WriteLine("null");
            else
                Console.WriteLine("not null");
            // null

            DateTime? dt2 = DateTime.Today;
            if (!dt2.HasValue)
                Console.WriteLine("null");
            else
                Console.WriteLine("not null");
            // not null
        }
    }
}

9. DateTime.TryParseExact()

if (DateTime.TryParseExact(BirthDate, "d/M/yyyy", new CultureInfo("en-US"), DateTimeStyles.None, out dateValue) == false)
{
    // Parse fail, do something
    ...
}