比较查询中的两种不同日期格式

时间:2011-12-28 20:12:41

标签: asp.net datetime timestamp ravendb

我必须将用户输入的日期“Dt”(mm / dd / yyyy格式)与RavenDB中的日期 - “ReleaseDate”(时间戳如“/ Date(1187668800000)/”)进行比较。为此,我使用以下代码几乎完成了工作,但我无需帮助来完成松散的结束......

如何比较这两个日期,以便我可以让查询成功运行。

    public ActionResult Calculation(DateTime? Dt)
    {             
        var store = new DocumentStore { Url = "http://localhost:80" };
        store.Initialize();

        var CalcModel = new CalcViewModel();

        using (var session = store.OpenSession())
        {       
         //Converting user entered date dt in mm/dd/yyyy format to total 
         //milliseconds - So that later I can compare this value to RavenDB
         //time stamp date format (older versions)

          DateTime d1 = new DateTime(1970, 1, 1);
          DateTime d2 = Dt.Value.ToUniversalTime();
          TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);

          double tmillisecs = ts.TotalMilliseconds; //Not yet using this value. 

          CalcModel.MoviesByDate = session.Query<Movies>()
                                   .Where(x => x.ReleaseDate.Ticks == ts.Ticks)            
                                   .Count();

          // this is where I need to compare two dates - ts.ticks gives the
          // required value of date (1187668800000) multiplied by 10000.
        }

        return View(CalcModel);

    }

现在,当我调试时,我知道ts.ticks正在显示什么值...和我在上面的代码注释中所说的那样,所需的值乘以10000.但我在运行时没有任何线索,是什么x.ReleaseDate中的值是x.ReleaseDate.Ticks是..我正确地这样做了。谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

嗯......我认为你严重误解了SQL日期的工作方式,以及它如何应用于.NET。关于日期的重点是它们以数字格式存储,而不是文本格式。因此,如果您有一个DateTime对象,它不会被存储为文本日期,它会被存储为一种数字类型,您可以将其转换为您想要的任何格式。

因为.net提供程序将数据库本机日期时间对象转换为DateTime对象,所以您可以本地比较它们。即:

DateTime d1 = new DateTime(1970, 1, 1);
CalcModel.MoviesByDate = session.Query<Movies>()
                               .Where(x => x.ReleaseDates.Date == d1.Date)
                               .Count();

无论RavenDB如何在内部存储日期,当在查询中实现DateTime对象时,它将采用本机.NET格式。

相关问题