C++/CLI Code Snippet - Convert Unix timestamp

C++/CLI Code Snippet - Convert Unix timestamp

C++/CLI Code Snippet - Convert Unix timestamp

C++/CLI code snippets convert date/time between DateTime and Unix timestamp. Most .Net base applications never use Unix timestamp, but if you want to create a application to interact with other application or sites, maybe built in PHP or Java, use these methods to convert Unix timestamp.

Bookmark:

C++/CLI Code Snippet - Convert Unix timestamp

These C++/CLI code snippets convert given Unix timestamp to DateTime and given DateTime to Unix timestamp. Unix timestamp is a long integer containing the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

This method converts a Unix timestamp to its DateTime equivalent. Method returns converted result as DateTime data type.

/// <summary>
/// Methods to convert Unix time stamp to DateTime
/// </summary>
/// <param name="_UnixTimeStamp">Unix time stamp to convert</param>
/// <returns>Return DateTime</returns>
DateTime UnixTimestampToDateTime(System::Int64 _UnixTimeStamp)
{
    return (DateTime(1970, 1, 1, 0, 0, 0)).AddSeconds(_UnixTimeStamp);
}


This method converts a DateTime to its Unix timestamp equivalent. Method returns converted result as long data type.

/// <summary>
/// Methods to convert DateTime to Unix time stamp
/// </summary>
/// <param name="_UnixTimeStamp">Unix time stamp to convert</param>
/// <returns>Return Unix time stamp as long type</returns>
System::Int64 DateTimeToUnixTimestamp(DateTime _DateTime)
{
    TimeSpan _UnixTimeSpan = (_DateTime - DateTime(1970, 1, 1, 0, 0, 0));
    return safe_cast<System::Int64>(_UnixTimeSpan.TotalSeconds);
}


Here are few simple examples showing how to use above methods (UnixTimestampToDateTime, DateTimeToUnixTimestamp) to convert date/time between DateTime and Unix timestamp.

// Convert current DateTime in Unix time stamp
Console::WriteLine("Current unix time stamp is : " + DateTimeToUnixTimestamp(DateTime::Now).ToString());

// convert Oct-07-1975 11:27 AM (15 Sec 37 MiliSec.) to Unix Time Stamp
Console::WriteLine("Oct-07-1975 11:27 AM (15 Sec 37 MiliSec.) to unix time stamp : " + DateTimeToUnixTimestamp(DateTime(1975, 10, 7, 11, 27, 15, 37)).ToString());

// convert given Unix time stamp to DateTime and update dateTimePicker value
dateTimePicker1->Value = UnixTimestampToDateTime(181913235);


C++/CLI Keywords Used:

  • TimeSpan
  • DateTime
  • UtcNow
  • TotalSeconds

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C++, CLI, Date/Time, Timestamp, Unix Time, Unix Timestamp, Convert Unix Timestamp
  • Programming Language : C++/CLI

External Resources:

Leave a comment