I have a GridView and I want to change the colour of the row if the date in a column is within a certain date range.
DateTime dt = new DateTime();
if (DateTime.TryParse(c.Text, out dt))
{
if (dt.Date >= DateTime.Now.AddDays(Mod.ValidUntilDays).Date && dt.Date <= DateTime.Now.AddDays(Mod.ValidUntilDays).Date)
{
e.Item.Style.Add("background-color", "#FF0303");
}
}
So the value coming from the grid is dt.Date is equal to 23/09/2016 00:00:00 and the date range I want to check is 25/09/2016 00:00:00. Mod.ValidUntilDays just adds 5 days to Today's date.
So what I am trying to do is check is23/09/2016 00:00:00 within the 5 day range which it is but the code never goes into the if statement.
you are asking the date to be >= 5-days-time and <= 5-days-time. So unless it == 5-days-time it'll return false. I think you mean this:
DateTime dt = new DateTime();
if (DateTime.TryParse(c.Text, out dt))
{
DateTime now = DateTime.Now;
if (dt.Date >= now.Date && dt.Date <= now.AddDays(Mod.ValidUntilDays).Date)
{
e.Item.Style.Add("background-color", "#FF0303");
}
}
Related
How can I select all weekends until the end of the year, with some criteria to be followed?
User input desired Weekend day:
18/12/2021
Software must out:
25/12/2022 (must be ignored)
01/01/2022
08/01/2022 (must be ignored)
15/01/2022
22/01/2022 (must be ignored)
29/01/2022 and so on...
What i have now:
public void GetWeekends() {
var lastWorkedWeekend = dateTimePicker1.Value;
var workedInSunday = checkBox1.Checked;
var list = new List < DateTime > ();
var weekends = GetDaysBetween(lastWorkedWeekend, DateTime.Today.AddDays(365)).Where(d => d.DayOfWeek == DayOfWeek.Saturday);
var selected = true;
for (int i = 0; i < weekends.Count(); i++) {
if (selected == false) {
list.Add(weekends.ElementAt(i));
selected = true;
} else {
selected = false;
}
}
}
I think I'd just scroll the input day forward until it was saturday (or calculate it, but i find the loop more self documenting than casting DayOfWeek to an int and factoring for sunday being 0) then add 14 days repeatedly. This skips over the 25th, etc..
var d = new DateTime(2021, 12, 18);
while(d.DayOfWeek != DayOfWeek.Saturday)
d += TimeSpan.FromDays(1);
while(d.Year == 2021){ //was your 2022 a typo? or maybe make this <= 2022.. I'm not sure what you want there..
d += TimeSpan.FromDays(14);
Console.WriteLine(d);
}
You might prefer DateTime.AddDays()..
Looks to me that you want to get the date of every second weekend from an initial date until the end of the year. In your example, you kinda bleed over to the next year.
public static void Main()
{
var dates = GetDateTimeRange(new DateTime(2021, 12, 18), new DateTime(2023, 1, 1), TimeSpan.FromDays(14));
foreach (var dateTime in dates.Skip(1))
{
Console.WriteLine(dateTime);
}
}
public static IEnumerable<DateTime> GetDateTimeRange(DateTime startingDate, DateTime endDate, TimeSpan interval)
{
var lastDate = startingDate;
while (lastDate < endDate)
{
yield return lastDate;
lastDate = lastDate.Add(interval);
}
}
This returns
01/01/2022 00:00:00
01/15/2022 00:00:00
01/29/2022 00:00:00
02/12/2022 00:00:00
02/26/2022 00:00:00
03/12/2022 00:00:00
03/26/2022 00:00:00
04/09/2022 00:00:00
04/23/2022 00:00:00
05/07/2022 00:00:00
05/21/2022 00:00:00
06/04/2022 00:00:00
06/18/2022 00:00:00
07/02/2022 00:00:00
07/16/2022 00:00:00
07/30/2022 00:00:00
08/13/2022 00:00:00
08/27/2022 00:00:00
09/10/2022 00:00:00
09/24/2022 00:00:00
10/08/2022 00:00:00
10/22/2022 00:00:00
11/05/2022 00:00:00
11/19/2022 00:00:00
12/03/2022 00:00:00
12/17/2022 00:00:00
12/31/2022 00:00:00
One approach is to use a method that creates an enumerable of dates. Once that's done you can use LINQ queries. If creating that enumerable is expensive you could just create one large range encompassing years and re-use it.
Or you might find better performance by just creating the range you need for each query.
public static class DateRanges
{
public static IEnumerable<DateOnly> GetRange(DateOnly start, DateOnly end)
{
for (var date = start; date <= end; date = date.AddDays(1))
{
yield return date;
}
}
}
It's not clear from your code what the criteria is, but this does what you described - all weekends from now to the end of the year.
var today = DateOnly.FromDateTime(DateTime.Today);
var lastDayOfYear = DateOnly.FromDateTime(new DateTime(DateTime.Today.Year, 12, 31));
var dates = DateRanges.GetRange(today, lastDayOfYear);
var weekendsOnly = dates.Where(date =>
date.DayOfWeek == DayOfWeek.Saturday);
Or if you prefer to create one date range and query it repeatedly:
// Big range of dates, 10 years into past and future.
// Create this once and re-use it
var dates = DateRanges.GetRange(
DateOnly.FromDateTime(DateTime.Today.AddYears(-10)),
DateOnly.FromDateTime(DateTime.Today.AddYears(10)));
var today = DateOnly.FromDateTime(DateTime.Today);
var lastDayOfYear = DateOnly.FromDateTime(new DateTime(DateTime.Today.Year, 12, 31));
var weekendsOnly = dates.Where(date =>
date >= today
&& date <= lastDayOfYear
&& date.DayOfWeek == DayOfWeek.Saturday);
In either case if you want every other Saturday you can add
.Where((date, i) => i % 2 == 0);
Or to maintain that readability you could put that in another extension like
public static IEnumerable<T> EveryOther<T>(this IEnumerable<T> source)
{
return source.Where((date, i) => i % 2 == 0);
}
so your query looks like
var everyOtherWeekend = dates
.Where(date =>
date >= today
&& date <= lastDayOfYear
&& date.DayOfWeek == DayOfWeek.Saturday)
.EveryOther();
I wouldn't position this as a better answer than those that iterate over a series of dates. The difference is that instead of having to write a method for any query you can start with a range of dates and then use LINQ to filter it. That makes it a little easier to read and to compose different queries.
Good day everyone. I'm new to C# but I can't seem to understand how DateTime work.
All I wanted to do is to check If a (givenday) = today and time is 7pm I wanted to return true. Is this the right way to do it?
Take note ActionDate is a field which is inputed by the user.
DateTime dateA = Convert.ToDateTime(ActionDate);
int a = dateA.Year;
int b = dateA.Month;
int c = dateA.Day;
int d = timeA.Hour;
int e = timeA.Minute;
var newDate = new DateTime(a, b, c, d, e, 0);
DateTime end = Convert.ToDateTime(newDate);
DateTime start = Convert.ToDateTime(A);
TimeSpan span = end.Subtract(start);
Decimal minutes = Convert.ToDecimal(span.TotalMinutes);
if
{
return true;
} else
{
return false;
}
Thank you in advance.
The way to check if a give date is today and is at 7pm is to use DateTime.Now.
Note that 19 is 7pm and 7 is 7am, the Hour property uses 24 hour format.
bool IsCurrentDayAnd7(DateTime dt) => dt.Date == DateTime.Now.Date && dt.Hour == 19;
As #TimSchmelter commented you could use DateTime.Today:
bool IsCurrentDayAnd7(DateTime dt) => dt.Date == DateTime.Today && dt.Hour == 19;
You can use Date property to compare date with current date.
if (newDate.Date == DateTime.Now.Date && newDate.Hour == 19)
{
return true;
}
You have made your code a bit too complicated. First, convert that user input to date, and compate it with current date and time.
DateTime dateA = Convert.ToDateTime(ActionDate);
if (dateA.Date == DateTime.Today && dateA.Hour == 19)
{
//it is current date and hour is 7pm
}
Alternatively, check if user's imput is ok, like this:
DateTime dateA;
if (!DateTime.TryParse(ActionDate, out dateA))
{
//alert user that he's entered wrong date
}
EDIT:
as Tim Schmelter noted, code's a bit more readable using DateTime.Today instead of DateTime.Now.Date
I want to filter some documents between a different date. First I tried comparing the dates directly, but the time (hour, minutes, second) doesn't have to be considered. Therefore only the date part is needed, but the following approach is wrong:
DateTime? fromDate = documentFilter.fromDate;
if (fromDate.HasValue) {
filterResults = filterResults.Where (d => d.LastModifiedAt.Value.Year >= fromDate.Value.Year
&& d.LastModifiedAt.Value.Month >= fromDate.Value.Month
&& d.LastModifiedAt.Value.Day >= fromDate.Value.Day);
}
DateTime? toDate = documentFilter.toDate;
if (toDate.HasValue) {
filterResults = filterResults.Where (d => d.LastModifiedAt.Value.Year <= toDate.Value.Year
&& d.LastModifiedAt.Value.Month <= toDate.Value.Month
&& d.LastModifiedAt.Value.Day <= toDate.Value.Day);
}
Consider the from date 8/15/2014 12:00:00 AM and the to date 9/15/2014 12:00:00 AM. If the document has the date 8/16/2014 10:06:25 AM it won't be in the results. The reason is that I directly compare each component (year, month, day). Because the day is 16 and 16 > 15 the last condition is not met.
How can I solve this? Should I set the time to one minute before midnight? Or should I calculate the difference?
Just use the DateTime.Date property:
if (fromDate.HasValue) {
filterResults = filterResults
.Where(d => d.LastModifiedAt.Date >= fromDate.Value.Date);
}
if (toDate.HasValue) {
filterResults = filterResults
.Where(d => d.LastModifiedAt.Date <= toDate.Value.Date);
}
DateTime has a Date property which returns a DateTime for the same day at midnight:
DateTime? fromDate = documentFilter.fromDate;
if (fromDate.HasValue)
filterResults = filterResults.Where(d => d.LastModifiedAt.Value.Date >= fromDate.Value.Date);
DateTime? toDate = documentFilter.toDate;
if (toDate.HasValue)
filterResults = filterResults.Where(d => d.LastModifiedAt.Value.Date <= toDate.Value.Date);
C# Code to calculate no.of days between two dates...I have start date in one textbox and end date in another textbox and i need to get no. of days between the two dates and to be displayed in third textbox and it should exclude holidays and weekends(saturday and sunday).
You can parse the textbox dates to date time object and then try something on the following lines.
DateTime startDate = new DateTime(2013, 03, 01);
DateTime endDate = DateTime.Today; // 12 March 2013
int totalDays = 0;
while (startDate <= endDate)
{
if (startDate.DayOfWeek == DayOfWeek.Saturday
|| startDate.DayOfWeek == DayOfWeek.Sunday)
{
startDate = startDate.AddDays(1);
continue;
}
startDate = startDate.AddDays(1);
totalDays++;
}
Console.WriteLine("Total days excluding weekends: {0}", totalDays);
var dateDiff = FirstDate - SecondDate;
double totalDays = dateDiff.TotalDays;
if you have two dates in textboxes viz textBox1 and textBox2
DateTime date1= new DateTime();
DateTime date2 = new DateTime();
double days;
bool isDate1Valid =DateTime.TryParse(textBox1.Text, out date1);
bool isDate2Valid =DateTime.TryParse(textBox2.Text, out date2);
if(isDate1Valid && isDate2Valid)
days = (date1-date2).TotalDays;
Edit
If you need to do it without looping, Here is how to do it..
If date difference is too large, looping may consume some amount of extra time.
Try this..
DateTime startdate = DateTime.Parse("somedate");
DateTime enddate = DateTime.Parse("somedate");
int daycount = 0;
while (startdate < enddate)
{
startdate = startdate.AddDays(1); // Fixed
int DayNumInWeek = (int)startdate.DayOfWeek;
if (DayNumInWeek != 0)
{
if (DayNumInWeek != 6)
{ daycount += 1; }
}
}
What I'm basically looking to do is monitor a period of time between 2 dates,
say 01/01/2011 to 04/04/2011.
I am then looking for a way to then compare 2 new dates, where if these new dates fall
between the above ones i can say assign a boolean a value and if they dont i wont.
so if 02/02/2011 to 03/03/2011 then assign the boolean wheras if outside then no.
??
You can just use normal compare operators with DateTime to do this.
For example
public bool Check(DateTime d1, DateTime d2)
{
DateTime StartDate = new DateTime(2011,1,1);
DateTime EndDate = new DateTime(2011,4,4);
return ((d1 >= StartDate && d1 <= EndDate) && (d2 >= StartDate && d2 <= EndDate));
}
This is a straight-forward as:
bool isInside = (testDate >= startDate && testDate <= endDate);
This example show how to check if a date is between two dates.
Code has been tested and works:
DateTime dtStart = new DateTime(2011, 02, 02);
DateTime dtEnd = new DateTime(2011, 03, 03);
if (DateTime.Now >= dtStart && DateTime.Now <= dtEnd)
{
// Date is within range
}