C# 将日期时间转换为 Int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17853491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert DateTime to Int
提问by A.T.
This is the sample I did in SQL Server
这是我在 SQL Server 中做的示例
SELECT CAST(CAST('2012-01-25 10:00:00.000' AS DATETIME) AS INT) + 2
Result is 40933
结果是 40933
How can I achieve this using c#? From where and how this integer comes?
我如何使用 c# 实现这一目标?这个整数来自哪里以及如何来的?
Reference: Convert from DateTime to INTbut this is what I need in c#
参考:从 DateTime 转换为 INT但这是我在 c# 中需要的
采纳答案by Klaus Byskov Pedersen
I don't understand why you would need to represent a DateTime
as an integer in C#, but you can use this method:
我不明白为什么您需要DateTime
在 C#中将 a 表示为整数,但您可以使用此方法:
public static int DateTimeToInt(DateTime theDate)
{
return (int)(theDate.Date - new DateTime(1900, 1, 1)).TotalDays + 2;
}
And you can use this method for the reverse operation:
您可以使用此方法进行反向操作:
public static DateTime IntToDateTime(int intDate)
{
return new DateTime(1900, 1, 1).AddDays(intDate - 2);
}
回答by burning_LEGION
extension to cast dateTime to timestamp
将 dateTime 转换为时间戳的扩展
public static int DateTimeToInt(this DateTime theDate)
{
int unixTime = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
return unixTime;
}
better to cast dateTime to long, use property DateTime.Ticks
for this
最好将 dateTime 转换为 long,DateTime.Ticks
为此使用属性