Code Examples In C#
Introduction
Date and time management is a crucial aspect of many web applications, whether scheduling events, logging user activity, or displaying localized times for a global audience.
C# provides robust support for handling date and time through its DateTime, DateTimeOffset, and TimeSpan structures, as well as classes like TimeZoneInfo in the .NET framework. Understanding these tools is essential for effectively managing temporal data in applications.
Get Current Time
Retrieving the current time is a fundamental task in software development, used in scenarios like logging, scheduling, time-stamping, and real-time processing.
In C#, the DateTime and DateTimeOffset structures provide straightforward ways to access the current time in both local and universal time (UTC). Understanding how to retrieve and manipulate the current time is essential for building time-aware applications.
Method:
1DateTime.Now
Example:
1using System;
2
3class Program
4{
5 static void Main()
6 {
7 DateTime currentTime = DateTime.Now;
8 Console.WriteLine("Current Date and Time: " + currentTime);
9 Console.WriteLine("Current Time Only: " + currentTime.ToString("hh:mm:ss tt"));
10 }
11}
Result:
1Current Date and Time: 10/15/2024 01:40:54
2Current Time Only: 01:40:54 AM
Get Unix Timestamp
Unix timestamps are a standard way of representing time as the number of seconds (or milliseconds) elapsed since the Unix epoch, which is January 1, 1970, at 00:00:00 UTC. They are widely used in web development for logging, scheduling, and synchronizing time across systems due to their simplicity and consistency.
In C#, working with Unix timestamps is straightforward, thanks to the DateTime, DateTimeOffset, and related classes.
Method:
1DateTimeOffset.ToUnixTimeSeconds()
2DateTimeOffset.ToUnixTimeMilliseconds()
Example:
1using System;
2
3class Program
4{
5 static void Main()
6 {
7 // Get the current time in UTC
8 DateTimeOffset now = DateTimeOffset.UtcNow;
9
10 // Get the Unix timestamp
11 long unixTimestamp = now.ToUnixTimeSeconds();
12 Console.WriteLine("Current Unix Timestamp: " + unixTimestamp);
13
14 // Get the Unix timestamp in milliseconds
15 long unixTimestampMilli = now.ToUnixTimeMilliseconds();
16 Console.WriteLine("Current Unix Timestamp in Milliseconds: " + unixTimestampMilli);
17 }
18}
Result:
1Current Unix Timestamp: 1734248726
2Current Unix Timestamp in Milliseconds: 1734248726852
Construct New Time
Creating new date and time objects is a core aspect of many applications, enabling developers to represent specific moments in time, schedule events, or perform date arithmetic.
C# provides multiple ways to create and initialize DateTime objects, giving developers the flexibility to work with both specific and default values.
Method:
1// Using the Constructor
2DateTime (int year, int month, int day, int hour, int minute, int second)
3
4// Using the Parse Method
5DateTime.Parse(string s)
6
7// For strict parsing of a specific format, use DateTime.ParseExact
8DateTime.ParseExact(string s, string format, IFormatProvider? provider)
Example:
1using System;
2using System.Globalization;
3
4class Program
5{
6 static void Main()
7 {
8 // Create a specific DateTime using Constructor
9 DateTime newDateTime = new DateTime(2023, 12, 25, 10, 30, 0);
10 Console.WriteLine("DateTime using constructor: " + newDateTime);
11
12 // Parse a date string into DateTime
13 string dateTimeString = "2023-12-25 10:30:00";
14 DateTime parsedDateTime = DateTime.Parse(dateTimeString);
15 Console.WriteLine("Parsed DateTime: " + parsedDateTime);
16
17 // Parse a date string with a specific format
18 string exactDateTimeString = "25-12-2023 10:30 AM";
19 DateTime specificDateTime = DateTime.ParseExact(
20 exactDateTimeString,
21 "dd-MM-yyyy hh:mm tt",
22 CultureInfo.InvariantCulture
23 );
24 Console.WriteLine("Parsed DateTime (Exact): " + specificDateTime);
25 }
26}
Result:
1DateTime using constructor: 12/25/2023 10:30:00
2Parsed DateTime: 12/25/2023 10:30:00
3Parsed DateTime (Exact): 12/25/2023 10:30:00
Convert Unix timestamp to Readable Date Time
Unix timestamps, representing the number of seconds since the Unix epoch (January 1, 1970, at 00:00:00 UTC), are commonly used in programming for their simplicity and efficiency.
However, they are not human-readable, making it necessary to convert them into a readable date and time format for display, logging, or reporting purposes
In C#, the DateTimeOffset class makes it easy to convert Unix timestamps to readable dates.
Method:
1DateTimeOffset.FromUnixTimeSeconds(long seconds)
Example:
1using System;
2
3class Program
4{
5 static void Main()
6 {
7 // Example Unix timestamp (in seconds)
8 long unixTimestamp = 1700000000;
9
10 // Convert Unix timestamp to DateTime (UTC)
11 DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(unixTimestamp);
12 DateTime dateTime = dateTimeOffset.UtcDateTime;
13
14 Console.WriteLine("Readable DateTime (UTC): " + dateTime);
15 }
16}
Result:
1Readable DateTime (UTC): 11/14/2023 22:13:20
Convert Date Time to Unix timestamp
Converting date-time objects into Unix timestamps is a common operation, often required for storing time values, performing calculations, or interacting with APIs and databases that use Unix time.
The DateTimeOffset structure in C# provides built-in methods to perform this conversion easily:
Method:
1DateTimeOffset.ToUnixTimeSeconds()
Example:
1using System;
2
3class Program
4{
5 static void Main()
6 {
7 // Define a specific DateTime
8 DateTime dateTime = new DateTime(2023, 12, 25, 10, 30, 0, DateTimeKind.Utc);
9
10 // Convert to Unix timestamp
11 long unixTimestamp = new DateTimeOffset(dateTime).ToUnixTimeSeconds();
12
13 Console.WriteLine("Unix Timestamp: " + unixTimestamp);
14 }
15}
Result:
1Unix Timestamp: 1703500200
Change Time Zone
Timezones play a critical role in applications that work with global users or time-sensitive data across different regions.
In C#, the .NET Framework provides robust tools for managing timezones using classes like DateTime, DateTimeOffset, and TimeZoneInfo.
Method:
1// Convert time between time zones
2DateTime.ConvertTime(DateTime dateTime, TimeZoneInfo srcTimeZone, TimeZoneInfo dstTimeZone);
3
4// Convert UTC time to a specific time zone
5DateTime.ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo dstTimeZone);
Example:
1using System;
2
3class Program
4{
5 static void Main()
6 {
7 try
8 {
9 // Define a specific date and time (as UTC)
10 DateTime utcTime = new DateTime(2023, 12, 25, 10, 30, 0, DateTimeKind.Utc);
11
12 // Find the desired time zone (e.g., Pacific Standard Time)
13 TimeZoneInfo targetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
14
15 // Convert UTC to the target time zone
16 DateTime targetTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, targetTimeZone);
17 Console.WriteLine("UTC Time: " + utcTime);
18 Console.WriteLine("Time in Pacific Standard Time: " + targetTime);
19
20 // Define a specific local time
21 DateTime localTime = new DateTime(2023, 12, 25, 10, 30, 0, DateTimeKind.Local);
22
23 // Find the target time zone (e.g., Eastern Standard Time)
24 TimeZoneInfo easternTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
25
26 // Convert the local time to the target time zone
27 DateTime easternTime = TimeZoneInfo.ConvertTime(localTime, TimeZoneInfo.Local, easternTimeZone);
28 Console.WriteLine("Local Time: " + localTime);
29 Console.WriteLine("Time in Eastern Standard Time: " + easternTime);
30 }
31 catch (TimeZoneNotFoundException) {
32 Console.WriteLine("Cannot find time zone in system");
33 }
34 }
35}
Result:
1UTC Time: 12/25/2023 AM 10:30:00
2Time in Pacific Standard Time: 12/25/2023 AM 2:30:00
3Local Time: 12/25/2023 AM 10:30:00
4Time in Eastern Standard Time: 12/24/2023 PM 9:30:00
Time Addition and Subtraction
Date-time addition and subtraction are essential operations for many time-based applications.
In C#, the DateTime and TimeSpan structures provide powerful and intuitive methods for performing addition and subtraction operations on date and time values.
Method:
1DateTime.Add(TimeSpan value)
2DateTime.AddDays(double value)
3DateTime.AddHours(double value)
4
5// calc time cost
6System.Diagnostics.Stopwatch
Example:
1using System;
2using System.Diagnostics;
3
4class Program
5{
6 static void Main()
7 {
8 // Define a base DateTime
9 DateTime dateTime = new DateTime(2023, 12, 25, 10, 30, 0);
10
11 // Create a TimeSpan for 2 days, 3 hours, and 30 minutes
12 TimeSpan timeSpan = new TimeSpan(2, 3, 30, 0);
13
14 // Add and subtract the TimeSpan
15 DateTime addedTimeSpan = dateTime.Add(timeSpan);
16 DateTime subtractedTimeSpan = dateTime.Subtract(timeSpan);
17
18 Console.WriteLine("Original DateTime: " + dateTime);
19 Console.WriteLine("After Adding TimeSpan: " + addedTimeSpan);
20 Console.WriteLine("After Subtracting TimeSpan: " + subtractedTimeSpan);
21
22 // Add or subtract time
23 DateTime addedDays = dateTime.AddDays(5); // Add 5 days
24 DateTime subtractedHours = dateTime.AddHours(-3); // Subtract 3 hours
25
26 Console.WriteLine("Original DateTime: " + dateTime);
27 Console.WriteLine("After Adding 5 Days: " + addedDays);
28 Console.WriteLine("After Subtracting 3 Hours: " + subtractedHours);
29
30 // Define two DateTime objects
31 DateTime startDate = new DateTime(2023, 12, 25, 10, 30, 0);
32 DateTime endDate = new DateTime(2023, 12, 30, 15, 45, 0);
33
34 // Subtract the dates to get a TimeSpan
35 TimeSpan difference = endDate - startDate;
36
37 Console.WriteLine("Start Date: " + startDate);
38 Console.WriteLine("End Date: " + endDate);
39 Console.WriteLine("Time Difference: " + difference);
40
41 // Create a Stopwatch instance
42 Stopwatch stopwatch = new Stopwatch();
43
44 // Start the stopwatch
45 stopwatch.Start();
46
47 // Example operation: Simulate a delay
48 System.Threading.Thread.Sleep(500); // 500 milliseconds
49
50 // Stop the stopwatch
51 stopwatch.Stop();
52
53 // Get the elapsed time
54 TimeSpan timeCost = stopwatch.Elapsed;
55 Console.WriteLine($"Time Cost: {timeCost.TotalMilliseconds} ms");
56 }
57}
Result:
1Original DateTime: 12/25/2023 10:30:00
2After Adding TimeSpan: 12/27/2023 14:00:00
3After Subtracting TimeSpan: 12/23/2023 07:00:00
4Original DateTime: 12/25/2023 10:30:00
5After Adding 5 Days: 12/30/2023 10:30:00
6After Subtracting 3 Hours: 12/25/2023 07:30:00
7Start Date: 12/25/2023 10:30:00
8End Date: 12/30/2023 15:45:00
9Time Difference: 5.05:15:00
10Time Cost: 500.3034 ms
Pause or sleep for a specific time
Pausing or delaying the execution of a program is a common requirement in various applications, such as implementing retries, creating animations, scheduling tasks, or rate-limiting requests.
C# provides various methods for pausing execution, whether synchronously or asynchronously, to suit different use cases.
Method:
1// Suspends the current thread
2Thread.Sleep(int millisecondsTimeout)
3
4// Using Task.Delay for Asynchronous Code
5Task.Delay(int millisecondsDelay)
Example:
1using System;
2using System.Threading;
3
4class Program
5{
6 static void Main()
7 {
8 Console.WriteLine("Start sleeping...");
9
10 // Sleep for 2 seconds
11 Thread.Sleep(2000);
12
13 Console.WriteLine("Woke up after 2 seconds!");
14 }
15}
Result:
1Start sleeping...
2Woke up after 2 seconds!