How to Get the Current Time in Milliseconds in C#
In this article, you’ll learn how to get the current time in milliseconds. We will discuss the date and time in programming, including the system date and time.
Next, we will discuss ways to get milliseconds. Finally, we will discuss some programming examples using milliseconds.
Date and Time in Programming
Date and time can be part of many entities. Many transactions require a current date and time.
For example, sale, purchase, joining, return, issue, etc. In many programs, we need comparison and calculations for date and time.
We can specify many examples, like finding out senior members, days between issue and return, the time between some activities like order and delivery, the time between start and cross of line in a race, to find typing speed, etc.
Every computer has a system clock, which remains active even if we switch off our computers. Almost every programming language gives some method to access system data and time.
Nowadays, across the world, many servers provide API to get dates and times using our code.
Most high programming languages provide a single object having both date and time; usually, it is referred to as now
. Similarly, C# offers different ways to access system data and time.
See an example:
using System;
class Test {
static void Main() {
DateTime date_time = DateTime.Now;
Console.WriteLine("Welcome, the current date and time is: " +
date_time.ToString("MM/dd/yyyy HH:mm:ss"));
}
}
Output:
Welcome, the current date and time is: 11/05/2022 07:49:27
Getting ideas about date and time, next we will discuss ways to get milliseconds in C#.
Milliseconds in C#
In C#, there is a DateTime
structure of the System namespace
that provides instant of time, i.e., mostly date and time of a day. Using a constructor, you can initialize the object by assigning a date-time value or parsing it from its string representation.
There are various ways to represent time in milliseconds; we will discuss some of them.
Using Millisecond
Property
The DateTime
structure provides a Millisecond
property through which we can get the component of milliseconds for a given date. For example:
using System;
class Test {
static void Main() {
DateTime date_time = DateTime.Now;
int ms = date_time.Millisecond;
Console.WriteLine("The current time is:" + date_time.ToString());
Console.WriteLine("The current time in milliseconds is: " + ms.ToString());
}
}
In the above example, we can see the date_time
object has been initialized with the current date-time, i.e., now
, used with the millisecond
’s property. This property returns an integer value in milliseconds of the present time.
Output:
The current time is:11/05/2022 04:17:00
The current time in milliseconds is: 736
We have created an object with the current date and time for demonstration purposes. Here is another method to extract milliseconds from the date_time
object.
Here, the first parameter is the year, the second parameter is the month, and the third parameter is the day.
Similarly, the fourth parameter is hours, the fifth is minutes, the sixth is seconds, and the last is milliseconds.
DateTime date_time = new DateTime(2022, 11, 4, 9, 20, 30, 120);
Console.WriteLine("Milliseconds: {0:fff}", date_time);
In the second line of the code, we are giving a format specifier to get milliseconds from the date_time
value. To read details of format specifiers, click here.
Output:
Milliseconds: 120
Using Date Time Parsing
We can convert the string representation of date-time into a DateTime
object by calling the static method Parse
of the same class. We can also get the date time value by calling the static Parse
method of DateTimeOffset
.
Next, we use a format specifier (already discussed) to get milliseconds. See the code:
using System;
class Test {
static void Main() {
string date_time_string = "10/23/2022 9:22:50.125 AM";
DateTime date_time = DateTime.Parse(date_time_string);
DateTimeOffset date_value = DateTimeOffset.Parse(date_time_string);
Console.WriteLine("Time in Milliseconds: {0}", date_time.ToString("fff"));
Console.WriteLine("\nTime in Milliseconds: {0}", date_value.ToString("fff"));
}
}
In the above code, you can see that we have used a string representation of date-time in the parsing method, which will automatically convert it to the corresponding date-time.
Output:
Time in Milliseconds: 125
Time in Milliseconds: 125
Using the Unix Time Method
The most convenient way to get time in milliseconds is to use a Unix timestamp. This timestamp returns several seconds that have elapsed since 00:00:00
UTC (Coordinated Universal Time
) on Jan 1970, excluding leap seconds.
The C# ToUnixTimeMilliseconds
method is used to get time in milliseconds. For example:
DateTimeOffset date = DateTimeOffset.UtcNow;
long milliseconds = date.ToUnixTimeMilliseconds();
Console.WriteLine(milliseconds);
Output:
1667624911885
We ran the same code after approximately 13
minutes and some seconds and got the value:
1667625703243
The difference is 791358
; if we divide this by 1000 milliseconds
, we will get 791.358
seconds. Further, if we divide by 60
seconds, we will get 13.1893
minutes.
We want to show that this method is not returning some constant value; instead, it returns elapsed seconds since Jan 1970.
Secondly, using this method, we can use the difference of values to measure milliseconds in some periods.
Custom Milliseconds Time Stamp
You can also measure your time using the Ticks
property in C#. The value range of ticks lies between minValue
and maxValue
.
The following example shows the use of ticks to get time in milliseconds.
long timeInMilliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
Console.WriteLine(timeInMilliseconds);
Output:
63803225681236
Using Stopwatch
Class
The Stopwatch
class in C# is used to measure the frequency of the task in the program. It measures the time elapsed and is helpful for code optimization.
Using the Stopwatch
class, you can calculate the time in milliseconds. For example:
using System;
using System.Threading;
using System.Diagnostics;
class Test {
static void Main() {
Stopwatch st = new Stopwatch();
st.Start();
Thread.Sleep(1000);
st.Stop();
Console.WriteLine("Time elapsed in Milliseconds: {0}", st.ElapsedMilliseconds);
}
}
Here, we use the Stopwatch
class from System.Diagnostics
. For demonstration purposes, we have to start the stopwatch and stop it after one second.
In between, we can do any required task. Here, we have intentionally called the Sleep
method of the Thread
class from the System.Threading
.
The Sleep
function creates time between the start/stop
methods. Finally, we are printing the property ElapsedMilliseconds
, representing the time elapsed between start and stop.
Output:
Time elapsed in Milliseconds: 1000
The output shows the time taken by the Sleep
method. We can recheck this by increasing the time in the Sleep
method. Next, we are going to discuss some coding examples using milliseconds.
Coding Examples Using Milliseconds in C#
We have a few coding examples using milliseconds in our program.
Example 1
First, we have an example of calculating the time the user is typing. Here, we have the code:
using System;
using System.Threading;
using System.Diagnostics;
class Test {
static void Main() {
Stopwatch st = new Stopwatch();
Console.WriteLine("Start typing without using enter key");
st.Start();
Console.ReadLine();
st.Stop();
Console.WriteLine("You have typed for {0}", st.ElapsedMilliseconds / 1000 + " seconds");
}
}
This code takes input from the user between the start
and stop
methods. In general, we take user input in some variable, whereas we are just trying to elapse some time between the start
and stop
function of the stopwatch
.
In the last line, we calculate the number of seconds, dividing elapsed milliseconds by 1000
. One sample run of this code is:
Start typing without using enter key
I am just typing and typing and typing
You have typed for 15 seconds
The first line of this output is a message to the user. In the second line, the user is typing some text before the Enter key is pressed, and the last line of the output shows the elapsed time in seconds.
Example 2
In this example, we are calculating the time to sort an array. We have declared an array size of 10000000
and called the sort
function to sort the array.
using System;
using System.Threading;
using System.Diagnostics;
class Array_Sort {
public static void Main() {
Random rn = new Random();
int[] arr = new int[10000000];
for (int i = 0; i < 1000000; i++) arr[i] = rn.Next(0, 50000);
Stopwatch st = new Stopwatch();
st.Start();
Array.Sort(arr);
st.Stop();
Console.WriteLine("Sorting time: {0}", st.ElapsedMilliseconds + " milliseconds");
}
}
Here, we have initialized the array randomly. We are calling the library function sort
to sort the array.
The function call is between the start
and the stop
functions.
In the last line, the time between start and stop, sorting time, is printed in milliseconds.
Output:
Sorting time: 2227 milliseconds
Example 3
The third example demonstrates milliseconds’ use in tracking the order process time. In practice, we have some formal way to do this; however, the supervisor will enter the key when the order is delivered to the customer.
Here, we are calculating the difference between order placement and delivery times.
using System;
class Order_Track {
public static void Main() {
DateTimeOffset date = DateTimeOffset.UtcNow;
DateTime date_time1 = DateTime.Now;
long order_placed_time = date_time1.Millisecond;
Console.WriteLine("Press Yes, when order is delivered");
Console.ReadLine();
DateTime date_time2 = DateTime.Now;
long order_deliver_time = date_time2.Millisecond;
long difference = order_deliver_time - order_placed_time;
Console.WriteLine("Order process time:" + difference + " milliseconds");
}
}
In the third main line, we have taken the system time and stored it in the variable order_placed_time
.
Next, we have a message for a supervisor or competent authority to enter the key when the order is delivered. After the input, we retook the system time.
In the previous line, we are printing this time. Finally, in the second last line, we calculate the difference between both times.
Output:
Press Yes, when order is delivered
Order process time:536 milliseconds
In this article, we comprehensively viewed the date and time. We have discussed multiple ways to get milliseconds in C#.
In the end, we have seen some examples of the application of milliseconds.