I have data in my database that contains the following filed.
Id | name | RegDate
1 John 2014-09-05
2 mike 2014-09-05
3 Duke 2014-10-14
I'm performing a query to count the number of values where the reg date is equal 09. 09 is the month of the date.
I'm trying to convert the date I store in db in a month format then get a new month of a system date to get the result.
Here is my query in linq but it keeps on giving the wrong count. please I need your help. thanks.
var CountPassengers = (from c in db.CountPassengerManifestViews where c.DepartureDate.Month.ToString()== DateTime.Now.AddMonths(-1).ToString("MM") select c).Count();
I would strongly recommend that you get rid of all the string manipulation. Your query doesn't conceptually have anything to do with strings, so why are you introducing them into the code?
You can write your query as:
int currentMonth = DateTime.Today.AddMonths(-1).Month;
var passengerCount = db.CountPassengerManifestViews
.Count(c => c.DepartureDate.Month == currentMonth);
However, that will only filter by month - it won't filter by month and year, so if you have data from 2013 that would be included too. It's more likely that you want something like:
DateTime oneMonthAgo = DateTime.Today.AddMonths(-1);
DateTime start = oneMonthAgo.AddDays(1 - oneMonthAgo.Day);
DateTime end = start.AddMonths(1);
var passengerCount = db.CountPassengerManifestViews
.Count(c => c.DepartureDate >= start &&
c.DepartureDate < end);
That way you're expressing a range of dates, rather than just extracting the month part.
where c.DepartureDate.Month == DateTime.Now.AddMonths(-1).Month
You don't compare string representation, because it's already converted into DateTime object, so it doesn't make sense to do it your way. This simple change should be enough.
I am not sure why you are doing the string manipulation but if you only want to compare the month part of the two dates then do the following:
where c.DepartureDate.Month== DateTime.Now.AddMonths(-1).Month
I think your code compares Month.ToString() that gives "9" with ToString("MM") that gives "09".
You could also improve by removing ".ToString()":
int lastMonth = DateTime.Now.AddMonths(-1).Month;
var CountPassengers = (from c in db.CountPassengerManifestViews where c.DepartureDate.Month == lastMonth select c).Count();
Regards
Try this
var CountPassengers = (from c in db.CountPassengerManifestViews
where c.DepartureDate.Month.ToString("MM")== DateTime.Now.AddMonths(-1).ToString("MM")
select c).Count();
var month = DateTime.Now.AddMonths(-1).Month;
var CountPassengers = db.CountPassengerManifestViews.Count(c => c.DepartureDate.Month == month);
Related
i have a column on my table "AbsenteeismDate" (type=date) when i want to get rows contain a date it return 0 row.
this is my C# code :
DateTime ClassDate = DateTime.Parse(lblDate.Content.ToString());
var Abs = dbs.GETAbsenteeisms.Where(a => a.AbsenteeismDate == ClassDate ).ToList();
i checked it there is a problem :
"AbsenteeismDate" on database and "ClassDate" aren't equal.
eg.
AbsenteeismDate=1396-05-31
and
ClassDate=1396-05-31 12:00:00 AM
how can i get Date without Time with DateTime type because AbsenteeismDate's type is date on my database.
sorry i can't speak English very well.
A DateTime always has a date and time portion, but if you want to get a DateTime of that date and the time value set to 12:00:00 midnight (00:00:00) use DateTime.Date:
var Abs = dbs.GETAbsenteeisms
.Where(a => a.AbsenteeismDate == ClassDate.Date)
.ToList();
You do just define date time but without the time:
string date = System.DateTime.Now.ToString("yyyy-MM-dd");
Use the Date property:
DateTime ClassDate = DateTime.Parse(lblDate.Content.ToString());
var date = ClassDate.Date;
Otherwise you will have to convert to string as follow
var date=ClassDate.ToString("yyyy-MM-dd");
This works for me:
string a = DateTime.Now.ToShortDateString();
ToShortDateString() converts the value of the current System.DateTime object to equivalent short date string representation. This means the Console output woulf be e.g. 01.01.2017
You can try like this byt setting the date format:
DateTime ClassDate = DateTime.Parse(lblDate.Content.ToString(("yyyy-MM-dd"));
var Abs = dbs.GETAbsenteeisms.Where(a => a.AbsenteeismDate == ClassDate ).ToList();
I could swear this was working two days ago, now it throws an exception...
I am checking against some data in a DataTable. I'm basically counting how many times a certain eventID is found within the last 15 minutes. Here's that code:
int startevents = trackingData
.Select("RHEventID = 3 AND RHDateEvent > #" + now + "#" ).Length;
I'm defining the 'now' variable just before that - looks like this:
DateTime now = DateTime.Now.AddMinutes(-15);
However this throws a String was not recognized as a valid DateTime exception. Here is an example of the data in the datatable, in the column for RHDateEvent:
2017-02-14 13:58:27 PM
(edit - yes this is only one date, not two, in the column)
So what am I doing wrong? Do I need to be converting this DateTime somehow?
I'd really recommend to use Linq-To-DataTable instead of the old and limited Select method:
DateTime in15minutes = DateTime.Now.AddMinutes(15);
var matchingRows = from row in trackingData.AsEnumerable()
where row.Field<int>("RHEventID) == 3
&& row.Field<DateTime>("RHDateEvent") > in15minutes
select row;
if you now just need the count use:
int matchingRowCount = matchingRows.Count();
This is more readable, powerful and supports compile time safety.
If your column is a not a DateTime- but a string-column you need to parse it:
...
&& DateTime.Parse(row.Field<string>("RHDateEvent"), CultureInfo.InvariantCulture) > in15minutes
It looks like the date time is duplicated...
2017-02-14 13:58:27 PM 2017-02-14 13:57:27 PM
instead of
2017-02-14 13:58:27 PM
If it's linq to entities use
var startevents = trackingData.Where(e => e.RHEventId = 3 && e.RHDateEvent >= DateTime.Now.AddMinutes(-15)).Count();
I would like to query the db for items with a date greater than or equal to a given date.
The date in the db is a datetime and records time.
If the user enters the search string "1/30/2014", they expect entries that occurred at any time on that date to be returned. However, anything that has a time after 12 am is not returned.
I know I could simply add a day to the search string, but is there a more appropriate way?
if (form["closedend"] != "")
{
DateTime d = DateTime.Parse(form["closedend"]);
traces = traces.Where(s => s.date_Closed >= d);
}
You can use the Date property to truncate the time part:
traces = traces.Where(s => s.date_Closed.Date <= d.Date);
On this way you'd include this day since both DateTimes are midnight.
Update if you use LINQ to Entities DateTime.Date is not supported, you could use this solution: Using DateTime in LINQ to Entities
.Where(s => EntityFunctions.TruncateTime(s.date_Closed) <= EntityFunctions.TruncateTime(d))
You said
with a date greater than or equal to a given date
but in your code you write
s.date_Closed <= d
I think you must change <= by >= to obtain dates greater or equal to d, now you're getting dates less or equal to d.
For this example you don't need neccessary any other dll. You can implement other function, which return bool, f.e:
public bool MyFunction(DateTime s)
{
DateTime d = DateTime.Parse(Your constructor);
return (s.date_Closed >= d);
}
var query = from obj in traces
where MyFunction(obj.date_Closed.Date)
select obj;
or:
var query = traces.Where(p => MyFunction(p.data_Closed.Date));
You can use DbFunctions.TruncateTime(StartDateTime) To remove the time from datetime.
if (form["closedend"] != "")
{
DateTime d = DateTime.Parse(form["closedend"]);
traces = traces.Where(s => DbFunctions.TruncateTime(s.date_Closed) >= DbFunctions.TruncateTime(d));
}
I would like to compare two dates excluding years.
Ex.
Input: FromDate: 01 March, ToDate: 05 March
then all records between these two dates should be come whether there is any year. It does not matter.
So please anyone can help me in this issue.
Thanks in advance.
If you are using LINQ and you want to create a list from querying the db you could do this?
public IEnumerable<Item> WithinTimeRange(DateTime begin, DateTime end)
{
var items = from a in context.Items
where a.Timestamp.Month.Equals(begin.Month) && a.Timestamp.Day
>= begin.Day && a.Timestamp.Month.Equals(end.Month) && a.Timestamp.Day <= end.Day
select a;
return items.ToList();
}
Personally I would create this method in your repository.
Whether you don't specify language and place where it will be used, I just give ju a hint.
Convert every datetime to a integer as: 10000 + 100 * month + day e.g.: 10306 as today.
Then you can ask for every data between 10301 and 10305 from your question.
I'm working with a collection of DateTime with all dates from Date A to Date B.
I will be handed a string which looks like 1234567, 1 is sunday, 2 is tuesday, etc.
Now, imagine I want to filter my dates collection using a string with the above configuration and we get the string 1004007, meaning we will have to filter our DateTime collection to only have dates which occur on a sunday, on a wednesday and a saturday.
How can I read the whole string, figure out which days I will be filtering from and then dynamically filter my collection according to those days of the week?
Give this a shot:
List<DateTime> dates = ...;
string filter = "1004007";
List<DateTime> filteredDates = dates.Where(d =>
filter.Contains(((int)d.DayOfWeek + 1).ToString())).ToList();
Or, if you like, you can first construct a list of days that are your filter rather than just using the String.Contains function. If your list of dates is very large, doing this work up front could help performance:
List<DateTime> dates = ...;
string filter = "1004007";
var daysOfWeek = filter.Distinct().Where(c => c != '0')
.Select(c => (DayOfWeek)(int.Parse(c.ToString()) - 1))
List<DateTime> filteredDates = (from d in dates
join dw in daysOfWeek on d.DayOfWeek equals dw
select d).ToList();
Convert the day of the week to an integer, then a string, and use Contains to see if it is in your input string:
string days = "1004007";
var result = datetimes
.Where(dt => days.Contains(((int)dt.DayOfWeek + 1).ToString()));