這是我在SQL Server轉換日期時間爲Int
SELECT CAST(CAST('2012-01-25 10:00:00.000' AS DATETIME) AS INT) + 2
結果所做的樣本是40933
我怎樣才能做到這一點使用C#?從哪裏和如何這個整數來?
參考:Convert from DateTime to INT,但是這是我需要在C#中
這是我在SQL Server轉換日期時間爲Int
SELECT CAST(CAST('2012-01-25 10:00:00.000' AS DATETIME) AS INT) + 2
結果所做的樣本是40933
我怎樣才能做到這一點使用C#?從哪裏和如何這個整數來?
參考:Convert from DateTime to INT,但是這是我需要在C#中
我不明白你爲什麼會需要代表DateTime
在C#中的一個整數,但你可以使用這個方法:
public static int DateTimeToInt(DateTime theDate)
{
return (int)(theDate.Date - new DateTime(1900, 1, 1)).TotalDays + 2;
}
你可以使用這個方法的反向操作:
public static DateTime IntToDateTime(int intDate)
{
return new DateTime(1900, 1, 1).AddDays(intDate - 2);
}
Thanku這麼多,我需要這個,因爲有數據庫中的字段表示DateTime作爲這個整數,我想它是爲了優化.... 和我正在開發窗口應用程序,這是現有應用程序的擴展......並且只有溝通的方式是通過數據庫服務,所以我需要在我的PCL的所有操作中執行 –
@阿倫:[壞習慣踢:處理日期/範圍查詢](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/16/bad-habits-to-kick-mishandling-date-range-queries.aspx) - 您應該* *不會**將日期存儲爲字符串或整數 - 您只是以這種方式尋求麻煩。使用'DATE'或'DATETIME'數據類型! –
@克勞斯請你提一下爲什麼這個+/- 2爲? – Rezoan
擴展到投日期時間爲timestamp
public static int DateTimeToInt(this DateTime theDate)
{
int unixTime = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
return unixTime;
}
更好的投日期時間長,使用屬性DateTime.Ticks
此
作爲一個時間戳? –
你爲什麼想在C#中做到這一點? –
,因爲我正在使用服務的應用程序,我不能在那裏使用sql程序 –