Compare two different date formats in a query - asp.net

I have to compare a user entered date, "Dt" (in mm/dd/yyyy format) with the date in RavenDB - "ReleaseDate" (time stamp like "/Date(1187668800000)/"). For this I am using the following code which almost gets the job done, but I need little help to finalize loose ends...
How can I compare the two dates so I can get the query to run successfully.
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);
}
Right now, when I debug I know what value ts.ticks is showing... and its like I said above in the code comments, the required value multiplied by 10000. But I have no clue at run time , what the value in x.ReleaseDate is or x.ReleaseDate.Ticks is.. am I doing this correctly. Thanks for the help.

Umm... I think you seriously misunderstand how SQL dates work, and how it applies to .NET. The whole point about dates is that they're stored in a numeric format, not a text one. So when you have a DateTime object, it's not stored as the text date, it's stored as a numeric type that you can convert to any format you want.
Because the .net provider converts database native datetime objects to DateTime objects, you can just compare them natively. ie:
DateTime d1 = new DateTime(1970, 1, 1);
CalcModel.MoviesByDate = session.Query<Movies>()
.Where(x => x.ReleaseDates.Date == d1.Date)
.Count();
Regardless of how RavenDB stores the dates internally, when the DateTime object is materialized in the query, it will be in native .NET format.

Related

Sage CRM - How to save a date with using the object returned from CRM.FindRecord()

Given this code:
var ToDateDate = new String(Request.Form("Comm_ToDateTime"));
ToDateDate = ToDateDate.split("/");
var newToDateTime = ToDateDate[2]+"-"+ToDateDate[1]+"-"+ToDateDate[0]+" "+Request.Form("Comm_ToDateTime_TIME")+":00.000";
CurrentCommunication("Comm_ToDateTime") = newToDateTime;
CurrentCommunication.SaveChanges();
How can i save the date?
This way the date (as Days, month and year) got saved but the hours, minutos does not.
The final output for the newToDateTime variable is 2016-19-09 08:50:00.000
if i use this value (2016-19-09 08:50:00.000) in a barehand SQL update, it works
Turns out that i have to build the Date object with the values and then use getVarDate() mehtod to to pass from a Date Javascriopt object to a record’s date field value which at the end it is the same i was doing :S
Found my answer in this Sage CRM Community

EntityFunction.TruncateTime not working in my query

I am using Linq to entityframework to query some infomration. I am trying to use entityfunction.truncatetime and it doesnt seem to work as expected. here is my sample query
From d In Request
Where d.Requestor= "XXXX" And d.ProcessedFlag = "N"
Select d.RequestID, RequestReason = d.RequestReason.ItemValue, RequestType = d.RequestType.ItemValue, RequestedDate = EntityFunctions.TruncateTime(d.RequestedMoveDate)
The requesteddate doesnt seem to truncate the time part and I am still getting the both Date and time.
Am I missing something here?
In .NET, the DateTime class actually represents both a date and a time. Internally, this is stored as a numeric value represented by the number of 100-nanosecond "ticks" since Midnight, January 1, 1001 AD. This number gets "converted" when it's displayed (either in output or in a debugger). This conversion is done via a format string.
Even if you truncate a DateTime's time portion, it still has a time... it's just 00:00:00, and if you don't want to see that time, you need to adjust your format string to not convert that.
Thus, if you do something like this: DateTime.Now.Date it will display `10/15/2012 00:00:00" if you use the default date conversion string (or whatever is the default format for your culture).
If you want to only display the Date portion, then you must do something like myDate.ToShortDateString() or myDate.ToString("d").
EntityFunctions is a set of tools designed to be used in Linq to Entities queries, because doing DateTime formatting is not normally allowed in a query.
For example, this code does not work:
var q = from x in dc where x.BirthDate == DateTime.Now.AddYears(-15).Date select x;
You have to do it like this:
var q = from x in dc
where x.Birthdate == EntityFunctions.TruncateTime(DateTime.Now.AddYears(-15))
select x;
This will then generate the correct SQL to do date comparisons in SQL code. This is what the EntityFunctions are designed for, not truncating dates in the select portion (although it does work). But, even though the date is truncated, it will still have a Time component, it will just be 00:00:00, and you must use a date format string to present it to your users in the manner you intend.
cant you use ToShortDateString() like below?
List<DateTime> time = new List<DateTime>();
time.Add(DateTime.Now);
var WhatDate = from date in time
select new { Date = date.ToShortDateString() };
In your case try this
From d In Request
Where d.Requestor= "XXXX" And d.ProcessedFlag = "N"
Select new{ RequestID = d.RequestID, RequestReason = d.RequestReason.ItemValue, RequestType = d.RequestType.ItemValue, RequestedDate = d.RequestedMoveDate.ToShortDateString()};

Is there a better way to encode a (MS) DateTime as an Int?

BACKGROUND (ok to ignore/skip):
I feel like there should be a better way to do what I'm doing, but I don't know what it is and I think my solution works, but I thought I'd ask in case there is something more elegant or faster or whatever.
I am developing a web page with MS Razor MVC which uses Html.DropDownList, which gives a pick list UI control which maps choices as display strings to integer ID codes. (I don't think I can have it map strings to DateTime values.)
But in a couple of cases, I want to choose from dates that are stored as DateTime objects. I realize I could make yet another table in memory that relates ID codes to DateTime values, but I thought instead (and also because I think I may want to encode dates as ints for yet another workaround of web page annoyances), I would encode the date as an int.
PROBLEM:
How best to convert the date of a DateTime object as an int value, and then later set a DateTime's date back to that date from the encoded int. The main ugliness of my solution is that DateTime provides a read-only DayOfYear function, but no way I know of to set a date back to (Date, DayOfYear), so I wrote a method with a loop, which is cute but probably slowish.
MY CURRENT (OK) SOLUTION:
public int encodeDate(DateTime date)
{
return ((date.Year - 2012) * 400) + date.DayOfYear;
}
public DateTime decodeDateCode(int dateCode)
{
int year = (dateCode / 400) + 2012;
int day = dateCode % 400;
// MS DateTime doesn't provide a direct reverse conversion for DayOfYear, so find it:
int month = 1;
int mThresh = DateTime.DaysInMonth(year, month);
while (day > mThresh)
{
day -= mThresh;
month++;
mThresh = DateTime.DaysInMonth(year, month);
}
DateTime dateValue = new DateTime(year, month, day);
return dateValue;
}
Ho about to format the timestamp as POSIX time (POSIX time / Unix time, see http://en.wikipedia.org/wiki/Unix_time)?
I had a similar problem myself and found a great solution here: Convert a Unix timestamp to a .NET DateTime
From the link:
DateTime ConvertFromUnixTimestamp(double timestamp)
{
}
double ConvertToUnixTimestamp(DateTime date)
{
}

Linq-to-entities date value in database is string

Personally, I know just enough Linq to be dangerous.
The task at hand is; I need to query the DAL and return a list of objects based on a date range. Sounds simple enough, however the date is a string, and for some reason it needs to stay a string.
I spent some time with this a while ago and got a solution working but I am iterating through a list of objects and selecting individual records by date one at a time, this is badddd! If the date range spans more than a few days its slow and I don't like it, and I've even busted a few of the Sr devs around here for doing iterative queries, so I definitely don't want to be a hypocrite.
Here is the crappy iteration way... each date pegs the database, which I hate doing.
- This works
DateTime start = Convert.ToDateTime(RecipientSearch.TransplantSearchStartDate);
DateTime end = Convert.ToDateTime(RecipientSearch.TransplantSearchEndDate);
var tempselectQuery = selectQuery;
while (start <= end)
{
tempselectQuery = selectQuery;
string sStart = Convert.ToDateTime(start).ToString(ResourceFormatting.DateOnly);
tempselectQuery = (ObjectQuery<DAL.Recipients>)tempselectQuery.Where(item => item.TransplantDate == sStart);
if (tempselectQuery.Count() != 0) TXPlistQueryDAL.AddRange(tempselectQuery.ToList());
start = start.AddDays(1);
}
Here is my attempt at trying to get my query to work in one db call
- This does not work... yet
DateTime start = Convert.ToDateTime(RecipientSearch.TransplantSearchStartDate);
DateTime end = Convert.ToDateTime(RecipientSearch.TransplantSearchEndDate);
List<string> sdates = new List<string>();
// Put my date strings in a list so I can then do a contains in my LINQ statement
// Date format is "11/29/2011"
while (start <= end)
{
string sStart = Convert.ToDateTime(start).ToString(ResourceFormatting.DateOnly);
sdates.Add(sStart);
start = start.AddDays(1);
}
// Below is where I get hung up, to do a .contains i need to pass in string, however x.TransplantDate
// includes time, so i am converting the string to a date, then using the EntityFunction to Truncate
// the time off, then i'd like to end up with a string, hence the .ToString, but, linq to entities
// thinks this is part of the sql query and bombs out... This is where I'm stumped on what to do next.
selectQuery =
(ObjectQuery<DAL.Recipients>)
from x in entities.Recipients
where sdates.Contains(EntityFunctions.TruncateTime(Convert.ToDateTime(x.TransplantDate)).ToString())
select x;
The error i get as follows:
I understand why I get the error, but I don't know the proper LINQ code to be able to acheive what I am trying to do. Any help will be greatly appreciated.
Ughh I feel dumb. I tried a bunch of tricky little things to get x.TransplantDate to just a date only string within my Linq query, E.G. 10/15/2011
where sdates.Contains(EntityFunctions.TruncateTime(Convert.ToDateTime(x.TransplantDate)).ToString())
Turns out it already is in the correct format in the database, and if i simplify it down to just
where sdates.Contains(x.TransplantDate) It works. The reason I wasnt getting any records returned was because I was testing date ranges that didnt have any data for those specific dates... UGHH.
So in conclusion this ended up working fine. And if anyone is doing something similar maybe you can learn from this example.
DateTime start = Convert.ToDateTime(RecipientSearch.TransplantSearchStartDate);
DateTime end = Convert.ToDateTime(RecipientSearch.TransplantSearchEndDate);
List<string> sdates = new List<string>();
while (start <= end)
{
string sStart = Convert.ToDateTime(start).ToString(ResourceFormatting.DateOnly);
sdates.Add(sStart);
start = start.AddDays(1);
}
selectQuery =
(ObjectQuery<DAL.Recipients>)
from x in entities.Recipients
where sdates.Contains(x.TransplantDate)
select x;

xml and condition by dateTime

XML
<CalendarFairs>
<CalendarFair>
<DateStart>2011-04-05T00:00:00</DateStart>
<DateEnd>2011-04-09T00:00:00</DateEnd>
<Title>aaaa</Title>
<IdExecutive>1</IdExecutive>
</CalendarFair>
<CalendarFair>
<DateStart>2011-04-16T00:00:00</DateStart>
<DateEnd>2011-04-19T00:00:00</DateEnd>
<Title>bbb</Title>
<IdExecutive>2</IdExecutive>
</CalendarFair>
<CalendarFairs>
Code
var elements = from element in doc.Descendants("CalendarFair")
where DateTime.Parse (element.Elements ("DateStart").ToString())==DateTime.Now
select new
{
dateStart = element.Element("DateStart").Value,
dateEnd=element.Element("DateEnd").Value,
title=element.Element("Title").Value,
idExcutive = element.Element("IdExecutive").Value ,
};
foreach (var item in elements)//send this error
{}
System.FormatException: The string was not recognized as a valid DateTime. There is a
unknown word starting at index 0.
why error?
Try to change it as follows:
var elements = from element in doc.Descendants("CalendarFair")
let start = element.Element("DateStart").Value
where DateTime.Parse (start)==DateTime.Now.Date
select new
{
dateStart = start,
dateEnd=element.Element("DateEnd").Value,
title=element.Element("Title").Value,
idExcutive = element.Element("IdExecutive").Value ,
};
EDIT: based on the XML you have posted the query above works pretty well. Try to test it with this input:
<CalendarFairs>
<CalendarFair>
<DateStart>2011-04-05T00:00:00</DateStart>
<DateEnd>2011-04-09T00:00:00</DateEnd>
<Title>aaaa</Title>
<IdExecutive>1</IdExecutive>
</CalendarFair>
<CalendarFair>
<DateStart>2011-03-20T00:00:00</DateStart>
<DateEnd>2011-04-19T00:00:00</DateEnd>
<Title>bbb</Title>
<IdExecutive>2</IdExecutive>
</CalendarFair>
</CalendarFairs>
Note that I have inserted today's start date. Actually I think the result was empty just because there weren't entries with actual date.
It sounds like one or more of your input <DateStart> strings is not in a valid DateTime format.
Can you post some sample input XML?
It may be that you need to provide the date format using ParseExact - http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

Resources