DateTime.AddMilliseconds() Method in C#


The DateTime.AddMilliseconds() method in C# is used to adds the specified number of milliseconds to the value of this instance. This method returns a new DateTime.

Syntax

Following is the syntax −

public DateTime AddMilliseconds (double mSec);

Above, mSec is the milliseconds to be added.

Example

Let us now see an example to implement the DateTime.AddMilliseconds() method −

using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 11, 10, 5, 0, 25);
      DateTime d2 = d1.AddMilliseconds(1000);
      System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
      System.Console.WriteLine("
New DateTime (After adding milliseconds) = {0:dd} {0:y}, {0:hh}:   {0:mm}:{0:ss} ", d2);    } }

Output

This will produce the following output −

Initial DateTime = 10 November 2019, 05:00:25
New DateTime (After adding milliseconds) = 10 November 2019, 05:00:26

Example

Let us now see another example to implement the DateTime.AddMilliseconds() method −

using System;
public class Demo {
   public static void Main(){
      DateTime d1 = new DateTime(2019, 10, 5, 9, 0, 10);
      DateTime d2 = d1.AddMilliseconds(-2000);
      System.Console.WriteLine("Initial DateTime = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d1);
      System.Console.WriteLine("
New DateTime (After subtracting milliseconds) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ", d2);    } }

Output

This will produce the following output −

Initial DateTime = 05 October 2019, 09:00:10
New DateTime (After subtracting milliseconds) = 05 October 2019, 09:00:08

Updated on: 11-Nov-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements