เมธอด DateTime.AddSeconds() ใน C# ใช้สำหรับเพิ่มจำนวนวินาทีที่ระบุเข้าไปในค่าของอินสแตนซ์นี้ โดยคืนค่า DateTime ใหม่
ไวยากรณ์
ไวยากรณ์มีดังนี้:
public DateTime AddSeconds (double sec);
พารามิเตอร์ sec คือจำนวนวินาทีที่จะเพิ่ม ใช้ค่าลบเพื่อลบวินาที
ตัวอย่าง
ตัวอย่างการเพิ่มวินาที:
using System;
public class Demo {
public static void Main(){
DateTime d1 = new DateTime(2019, 10, 25, 6, 20, 40);
DateTime d2 = d1.AddSeconds(25);
System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
System.Console.WriteLine("\nNew DateTime (After adding seconds) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
}
}
ผลลัพธ์
โค้ดจะแสดงผลดังนี้:
Initial DateTime = 25 October 2019, 06:20:40 New DateTime (After adding seconds) = 25 October 2019, 06:21:05
ตัวอย่างเพิ่มเติม
ตัวอย่างการลบวินาที:
using System;
public class Demo {
public static void Main(){
DateTime d1 = new DateTime(2019, 10, 25, 6, 20, 40);
DateTime d2 = d1.AddSeconds(-10);
System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
System.Console.WriteLine("\nNew DateTime (After subtracting seconds) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
}
}
ผลลัพธ์
โค้ดจะแสดงผลดังนี้:
Initial DateTime = 25 October 2019, 06:20:40 New DateTime (After subtracting seconds) = 25 October 2019, 06:20:30