How to convert a timestamp to a date format in C#?
In C#, time stamps can be converted to date format by using the DateTime constructor or the ParseExact method.
Option 1:
Method 1: Implementing the DateTime constructor.
// 假设时间戳是一个long类型的值
long timestamp = 1598918400; // 2020年9月1日的时间戳
// 将时间戳转换为DateTime对象
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp);
// 输出日期格式
string date = dateTime.ToString("yyyy-MM-dd");
Console.WriteLine(date); // 输出:2020-09-01
Method 2: Utilize the ParseExact method.
// 假设时间戳是一个字符串类型的值
string timestampStr = "1598918400"; // 2020年9月1日的时间戳
// 将时间戳字符串转换为DateTime对象
DateTime dateTime = DateTime.ParseExact(timestampStr, "yyyy-MM-dd HH:mm:ss", null);
// 输出日期格式
string date = dateTime.ToString("yyyy-MM-dd");
Console.WriteLine(date); // 输出:2020-09-01
The choice between the two methods of converting a timestamp to a date format depends on your needs and the type of timestamp being used.