2017-10-17 50 views
-4

我有日期時間之間的區別計算差值爲int

我計算它在車型

public partial class Park 
{ 
    public int parkId { get; set; } 
    public decimal Longitude { get; set; } 
    public decimal Latitude { get; set; } 
    public Nullable<System.DateTime> TimeStart { get; set; } 
    public Nullable<System.DateTime> TimeEnd { get; set; } 
    [NotMapped] 
    public TimeSpan? Difference { get { return TimeEnd - TimeStart; } } 
} 

並在此之後我把它稱爲後端

var items = ctx.Parks.AsEnumerable().Select(
       x => new { 
        lng = x.Longitude, 
        lat = x.Latitude, 
        difference = x.Difference 
       }).ToList(); 

但我得到這{ lng = 50.4558539000, lat = 30.5148783000, difference = {00:05:00} }

如果我使用TotalMinutes,有這

嚴重級代碼說明項目文件行抑制狀態 錯誤CS1061'TimeSpan?'不包含'TotalMinutes'的定義,也沒有包含接受'TimeSpan'類型的第一個參數的擴展方法'TotalMinutes'?可以發現(?是否缺少using指令或程序集引用)GoogleMapsAsp_Net C:\用戶\ nemes \源\回購\ GoogleMapsAsp_Net \ GoogleMapsAsp_Net \ \控制器28 HomeController.cs主動

但我需要的差異在int分鐘內,我該如何做到這一點?

+1

你想要兩天之間的天數? –

+2

那麼你想要什麼單位?你會期待什麼結果5分鐘的差異?5秒的差距? 5小時的差異? –

+1

具體什麼* int *值應該是'00:05:00'? – David

回答

1

基本上可以做到之一:

difference = (int?)(x.Difference?.TotalMinutes) 

在這種情況下,您的答案將爲可空(int)(int?),因此它將支持差異爲空的可能性(在此情況下爲null)。

或者,如果你需要有在這種情況下的默認值,說-1,這樣做:

difference = (int)(x.Difference?.TotalMinutes ?? -1) 

延伸閱讀:

  1. Null propagation operator
  2. ?? operator
+1

其實,['TotalMinutes'](https://msdn.microsoft.com/en-us/library/system.timespan.totalminutes(v = vs.110).aspx)會返回一個double,而不是int 。 –

+0

你是對的,是從記憶中做到這一點。固定。 – decPL

-3

您可以使用TimeSpanTotalSeconds/TotalMinutes/etc屬性。

var items = ctx.Parks.AsEnumerable().Select(
       x => new { 
        lng = x.Longitude, 
        lat = x.Latitude, 
        difference = x.Difference.TotalSeconds //Just add .TotalSeconds 
       }).ToList(); 

需要注意的是,你將不得不投你的TimeSpan?TimeSpan

+1

'我需要差異在int':它是否意味着op需要秒輸出? –