我想在我的应用程序中获得有效的时间戳,所以我写道:
public static String GetTimestamp(DateTime value)
{
return value.ToString("yyyyMMddHHmmssffff");
}
// ...later on in the code
String timeStamp = GetTimestamp(new DateTime());
Console.WriteLine(timeStamp);
Run Code Online (Sandbox Code Playgroud)
输出:
000101010000000000
Run Code Online (Sandbox Code Playgroud)
我想要的东西:
20140112180244
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
eka*_*kad 171
您的错误是使用new DateTime()
,它返回0001年1月1日00:00:00.000而不是当前日期和时间.获取当前日期和时间的正确语法是DateTime.Now,因此更改此:
String timeStamp = GetTimestamp(new DateTime());
Run Code Online (Sandbox Code Playgroud)
对此:
String timeStamp = GetTimestamp(DateTime.Now);
Run Code Online (Sandbox Code Playgroud)
Moh*_*bdo 30
var Timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
Run Code Online (Sandbox Code Playgroud)
var timestamp = DateTime.Now.ToFileTime();
Run Code Online (Sandbox Code Playgroud)
这个答案本身并不"更好",但它是一个替代答案,提供类似于已经提供的结果,同时不那么冗长.即使它不是unix时间,windows filetime仍可用于个别化不同的事务.
对于UTC:
string unixTimestamp = Convert.ToString((int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
Run Code Online (Sandbox Code Playgroud)
对于本地系统:
string unixTimestamp = Convert.ToString((int)DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
Run Code Online (Sandbox Code Playgroud)
小智 5
Int32 unixTimestamp = (Int32)(TIME.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
Run Code Online (Sandbox Code Playgroud)
“TIME”是您想要获取其 Unix 时间戳的 DateTime 对象。