Unix Timestamps with C#

Unix timestamps are very easy to use and straightforward to implement in C# (C Sharp).

Current Unix timestamp (in seconds) with C#

             
            using System;

            public class Example
            {
                public static void Main()
                {
                    long timestamp = (long)DateTime.UtcNow.Subtract(DateTime.UnixEpoch).TotalSeconds;
                    Console.WriteLine("Unix timestamp: " + timestamp);
                }
            }
            
        
Run this code online.

Date to Unix timestamp with C#

            
            using System;
            using System.Globalization;
                                    
            public class Program
            {
                public static void Main()
                {	
                    CultureInfo culture = new CultureInfo("en-US");
                    DateTime tempDate = Convert.ToDateTime("1/1/2025 12:45:12 PM", culture);
                    long timestamp = (long)((TimeZoneInfo.ConvertTimeToUtc(tempDate) - new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds);
                    Console.WriteLine("Unix timestamp: " + timestamp);
                }
            }
            
        
Run this code online.

Convert Unix timestamp to date with C#

            
            using System;

            public class Example
            {
                public static void Main()
                {
                    long timestamp = (long)1692194767;
                    DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                    dateTime = dateTime.AddSeconds( timestamp ).ToLocalTime();
                    Console.WriteLine("Locale date String: : " + dateTime);
                }
                    
            }
            
        
Run this code online.