Time Functions in C#



The DateTime has methods and properties for Date and Time as well like how to get the number of hours or minutes of a day, etc.

Let us only focus on the time functions −

Refer MSDN (Microsoft Developer Network) for all the functions −

Sr.No. Method & Properties
1 AddDays(Double)
Returns a new DateTime that adds the specified number of days to the value of this instance.
2 AddHours(Double)
Returns a new DateTime that adds the specified number of hours to the value of this instance.
3 AddMilliseconds(Double)
Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.
4 AddMinutes(Double)
Returns a new DateTime that adds the specified number of minutes to the value of this instance.
5 AddSeconds(Double)
Returns a new DateTime that adds the specified number of seconds to the value of this instance.
6 AddYears(Int32)
Returns a new DateTime that adds the specified number of years to the value of this instance.

Let us learn about a Time function i.e. AddMilliseconds(Double) to add the specified number of milliseconds to the value of this instance.

Example

 Live Demo

using System;

public class Demo {
   public static void Main() {
      string dateFormat = "MM/dd/yyyy hh:mm:ss.fffffff";
      DateTime dateCurrent = new DateTime(2018, 7, 23, 13, 0, 0);
      Console.WriteLine("Original date: {0} ({1:N0} ticks)
", dateCurrent.ToString(dateFormat),          dateCurrent.Ticks);       DateTime dateNew = dateCurrent.AddMilliseconds(1);       Console.WriteLine("Next date: {0} ({1:N0} ticks)", dateNew.ToString(dateFormat),          dateNew.Ticks);    } }

Output

Original date: 07/23/2018 01:00:00.0000000 (636,679,476,000,000,000 ticks)
Next date: 07/23/2018 01:00:00.0010000 (636,679,476,000,010,000 ticks)
Updated on: 2020-06-20T16:02:46+05:30

862 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements