Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
DateTime.AddSeconds() Method in C#
The DateTime.AddSeconds() method in C# is used to add the specified number of seconds to the value of this instance. This returns a new DateTime object without modifying the original DateTime instance.
Syntax
Following is the syntax −
public DateTime AddSeconds(double sec);
Parameters
sec − A double value representing the number of seconds to be added. If you want to subtract seconds, then set a negative value. The value can include fractional seconds.
Return Value
This method returns a new DateTime object that represents the date and time after adding the specified seconds. The original DateTime instance remains unchanged.
Using AddSeconds() to Add Seconds
Example
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("New DateTime (After adding seconds) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
}
}
The output of the above code is −
Initial DateTime = 25 October 2019, 06:20:40 New DateTime (After adding seconds) = 25 October 2019, 06:21:05
Using AddSeconds() to Subtract Seconds
Example
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("New DateTime (After subtracting seconds) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);
}
}
The output of the above code is −
Initial DateTime = 25 October 2019, 06:20:40 New DateTime (After subtracting seconds) = 25 October 2019, 06:20:30
Using Fractional Seconds
Example
using System;
public class Demo {
public static void Main() {
DateTime d1 = new DateTime(2019, 10, 25, 6, 20, 40, 500);
DateTime d2 = d1.AddSeconds(2.75);
Console.WriteLine("Initial DateTime = {0:yyyy-MM-dd HH:mm:ss.fff}", d1);
Console.WriteLine("New DateTime (After adding 2.75 seconds) = {0:yyyy-MM-dd HH:mm:ss.fff}", d2);
}
}
The output of the above code is −
Initial DateTime = 2019-10-25 06:20:40.500 New DateTime (After adding 2.75 seconds) = 2019-10-25 06:20:43.250
Conclusion
The DateTime.AddSeconds() method provides a convenient way to add or subtract seconds from a DateTime instance. It returns a new DateTime object, preserving immutability, and accepts both positive and negative values including fractional seconds for precise time calculations.
