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

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

Phương thức DateTime.AddSeconds() trong C# được dùng để thêm số giây được chỉ định vào giá trị của thể hiện này. Phương thức trả về một DateTime mới.

Cú pháp

Cú pháp như sau:

public DateTime AddSeconds(double sec);

Tham số sec là số giây cần thêm. Để trừ giây, sử dụng giá trị âm.

Ví dụ 1 - Thêm 25 giây

using System;

public class Demo
{
    public static void Main()
    {
        DateTime d1 = new DateTime(2019, 10, 25, 6, 20, 40);
        DateTime d2 = d1.AddSeconds(25);
        Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
        Console.WriteLine("\nNew DateTime (After adding seconds) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
    }
}

Kết quả

Initial DateTime = 25 October 2019, 06:20:40
New DateTime (After adding seconds) = 25 October 2019, 06:21:05

Ví dụ 2 - Trừ 10 giây

using System;

public class Demo
{
    public static void Main()
    {
        DateTime d1 = new DateTime(2019, 10, 25, 6, 20, 40);
        DateTime d2 = d1.AddSeconds(-10);
        Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
        Console.WriteLine("\nNew DateTime (After subtracting seconds) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
    }
}

Kết quả

Initial DateTime = 25 October 2019, 06:20:40
New DateTime (After subtracting seconds) = 25 October 2019, 06:20:30