Analysis of Basic Usage Examples of C Time Stamps

  • 2021-07-24 11:35:51
  • OfStack

This article illustrates the basic usage of C # timestamp. Share it for your reference. The details are as follows:

1. How does C # generate a timestamp


/// <summary> 
///  Get a timestamp  
/// </summary> 
/// <returns></returns> 
public static string GetTimeStamp() 
{ 
  TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); 
  return Convert.ToInt64(ts.TotalSeconds).ToString(); 
} 

It is often found that one timestamp is used to represent time in many places. For example, 1370838759 means 12:32:39 on June 10, 2013. We need a tool to easily convert this time format

2. What is a timestamp?

Time stamp, also known as Unix Stamp. The number of seconds elapsed since January 1, 1970 (midnight at UTC/GMT), excluding leap seconds.

3. Convert C # timestamp to normal time


//  Timestamp to C# Format time 
private DateTime StampToDateTime(string timeStamp)
{
  DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  long lTime = long.Parse(timeStamp + "0000000");
  TimeSpan toNow = new TimeSpan(lTime);
  return dateTimeStart.Add(toNow);
}
// DateTime Time format is converted to Unix Timestamp format 
private int DateTimeToStamp(System.DateTime time)
{
  System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
  return (int)(time - startTime).TotalSeconds;
}

I hope this article is helpful to everyone's C # programming.


Related articles: