The system time and UNIX time stamp in C are converted to each other

  • 2021-10-11 19:22:13
  • OfStack

In the process of project development, sometimes different programs call data to each other, and the data will inevitably contain time. For example, ASP. NET calls PHP, which requires 1 processing when it comes to time. PHP programs generally access UNIX time, unlike ASP. NET, which stores years, months, days, hours and seconds, so it needs to do 1 down conversion. The code is as follows:

1. Convert system time to UNIX timestamp

DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970,1,1));
DateTime dtNow = DateTime.Parse(DateTime.Now.ToString());
TimeSpan toNow = dtNow.SuBTract(dtStart);
string timeStamp = toNow.Ticks.ToString();
timeStamp = timeStamp.Substring(0,timeStamp.Length - 7);

2. Convert UNIX timestamp to system time

string timeStamp = "1288368000";
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970,1,1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
DateTime dtResult = dtStart.Add(toNow);

These two methods are relatively simple, so you can encapsulate them into static functions and call them directly.


Related articles: