Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Phương thức DateTime.Equals() trong C#

Phương thức DateTime.Equals() trong C# kiểm tra xem hai đối tượng DateTime có bằng nhau hay không. Trả về TRUE nếu bằng nhau, ngược lại FALSE.

Cú pháp

public static bool Equals(DateTime date1, DateTime date2);

Ví dụ 1

using System;
public class Demo
{
    public static void Main()
    {
        DateTime d1 = new DateTime(2019, 09, 10, 5, 15, 25);
        DateTime d2 = d1.AddMonths(25);
        Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
        Console.WriteLine("\nNew DateTime (After adding months) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
        bool res = DateTime.Equals(d1, d2);
        if (res)
            Console.WriteLine("\ndate1 = date2. ");
        else
            Console.WriteLine("\ndate1 is not equal to date2. ");
    }
}

Đầu ra

Initial DateTime = 10 September 2019, 05:15:25
New DateTime (After adding months) = 10 October 2021, 05:15:25
date1 is not equal to date2.

Ví dụ 2

using System;
public class Demo
{
    public static void Main()
    {
        DateTime d1 = new DateTime(2019, 11, 11, 7, 15, 30);
        DateTime d2 = new DateTime(2019, 11, 11, 7, 15, 30);
        Console.WriteLine("DateTime1 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
        Console.WriteLine("\nDateTime2 = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
        bool res = DateTime.Equals(d1, d2);
        if (res)
            Console.WriteLine("\ndate1 = date2 ");
        else
            Console.WriteLine("\ndate1 is not equal to date2 ");
    }
}

Đầu ra

DateTime1 = 11 November 2019, 07:15:30
DateTime2 = 11 November 2019, 07:15:30
date1 = date2