簡體   English   中英

查找表中的日期與午夜之間的差異(ASP.NET MVC)

[英]Find difference between date in table and midnight (ASP.NET MVC)

我有數據表

這是模特

public partial class Logging
{
    public string Imei { get; set; }
    public Nullable<System.DateTime> CurDateTime { get; set; }
    public Nullable<System.DateTime> GPSDateTime2 { get; set; }
    public Nullable<decimal> Latitude2 { get; set; }
    public Nullable<decimal> Longitude2 { get; set; }
    public string Speed { get; set; }
    public Nullable<int> Datatype { get; set; }
    public int Id { get; set; }
    [NotMapped]
    public TimeSpan? FirstStartDifference { get { return CurDateTime - DateTime.Today; } }
    [NotMapped]
    public int coeff = 2;
}

我需要在分鍾內找到CurDateTime和午夜之間的數據

但是public TimeSpan? FirstStartDifference { get { return CurDateTime - DateTime.Today; } } public TimeSpan? FirstStartDifference { get { return CurDateTime - DateTime.Today; } } public TimeSpan? FirstStartDifference { get { return CurDateTime - DateTime.Today; } }不對,因為DateTime.Today是今天,而我在-得到了區別。

在控制器上我這樣做

   public JsonResult GetStops()
    {
        using (var ctx = new GoogleMapTutorialEntities())
        {
            var firstitem = ctx.Loggings.Where(x => x.Datatype == 1).AsEnumerable().Select(
                x => new
                {
                    lng = x.Longitude2,
                    lat = x.Latitude2,
                    difference = (int)(x.FirstStartDifference?.TotalMinutes ?? -1) * x.coeff
                }).FirstOrDefault();

            return Json(firstitem, JsonRequestBehavior.AllowGet);
        }
    }

如何正確計算差異

你可以得到兩個時間的差

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

您可以使用小時,分鍾和秒屬性,並根據這些值構造新的DateTime,這將是您所需的區別。 或者,您可以使用0小時0分0秒創建新的DateTime並進行減法。

這是工作示例

您可以根據需要進行計算或由其他答案描述,但是對結果使用.Duration() Duration方法將返回絕對結果,而不是負數。

四行代碼:

public TimeSpan? FirstStartDifference 
{
    get 
    {
        if (!CurDateTime.HasValue)
        {
            return null
        }

        return (CurDateTime - DateTime.Today).Duration(); 
    } 
}

如果只希望從DateTime對象獲得日期值,則只需使用Date屬性,而不要創建一個新的屬性。

例如

var myDateTime = DateTime.Now;
var myDate = myDateTime.Date;

因此,您要從DateTime.Today減去當前日期為00:00的CurDateTime減去10/18/2017 8:05:38 AM。 當然,這將最終得到負值,因為CurDateTime小於今天的日期。

您需要從CurDateTime的午夜日期時間中減去它。 像這樣:

var midnight = new DateTime(CurDateTime.Year, CurDateTime.Month, CurDateTime.Day, 00, 00, 00);
var difference = CurDateTime - midnight;
var inMin = difference.TotalMinutes;

在您的情況下:

 [NotMapped]
 public TimeSpan? FirstStartDifference
 {
    get
    {
      if(CurDateTime != null)
      {
        var midnight = new DateTime(CurDateTime.Year, CurDateTime.Month, CurDateTime.Day, 00, 00, 00);
        var difference = CurDateTime - midnight
        return difference;
      }
      return null;
    }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM