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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:39:24  来源:igfitidea点击:

Convert DateTime to Int

c#sqlsql-serverdatetimeint

提问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 DateTimeas 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.Ticksfor this

最好将 dateTime 转换为 long,DateTime.Ticks为此使用属性