DotNET Schools

Blogs & Tutorials for Microsoft.NET and Leading web Technologies

Converting DateTime to Unix TimeStamp in Local Time

The unix time stamp is the number of seconds between a particular date and the Unix Epoch. The counts of Unix Epoch start on 01-Jan-1970 at UTC.

But sometimes we need to calculate the time stamp as per local time. Suppose an event has been occurred on 01-Jan-1990 00:00 IST (GMT + 5:30) and I convert it to time stamp as per UTC then here will be difference of 5:30 hrs. To get exact time stamp with 00:00 hrs difference I am converting it as per local time.

Way1 :

/// <summary> /// Convers to unix date time stamp way1. /// </summary> /// <param name="dateToConvert">The date to convert.</param> /// <returns></returns> public static long ConverToUnixDateTimeStampWay1(DateTime dateToConvert) { TimeSpan timeSpan = (dateToConvert.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local)); return Convert.ToInt64(timeSpan.TotalSeconds); }









/// <summary>   
/// Convers to unix date time stamp way1.
/// </summary>
/// <param name="dateToConvert">The date to convert.</param>
/// <returns></returns>
public static long ConverToUnixDateTimeStampWay1(DateTime dateToConvert) {
TimeSpan timeSpan = (dateToConvert.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Local));
return Convert.ToInt64(timeSpan.TotalSeconds); }







  1.   

Way2 :

  1. /// <summary>   
  2. /// Convers to unix date time stamp way2.   
  3. /// </summary>   
  4. /// <param name="dateToConvert">The date to convert.</param>   
  5. /// <param name="dateFormat">The date format.</param>   
  6. /// <returns></returns>   
  7. public static string ConverToUnixDateTimeStampWay2(string dateToConvert, string dateFormat)  
  8. {  
  9.     DateTime dtToConvert = new DateTime();  
  10.     DateTime.TryParseExact(dateToConvert, dateFormat, null, DateTimeStyles.AssumeLocal, out dtToConvert);  
  11.   
  12.     //in the below statement DateTime.Parse("01 /01/1970 00:00:00") is not safe and will throw exception while changing DateTimeFormat   
  13.     long ticks = dtToConvert.Subtract(new TimeSpan(1, 0, 0)).Ticks - DateTime.Parse("01/01/1970 00:00:00").Ticks;  
  14.     ticks /= 10000000; //Convert windows ticks to seconds   
  15.     return ticks.ToString();  
  16. }  

In both of the above methods you can see that I am storing all data in long (System.Int64) instead of int (System.Int32).

If I store time stamp in int (System.Int32) then it will throw exception for any date after 19-January-2038.