Need specific dates in C# - c#

I have an application in WindowsForms where I have to add exceptions if the day is 25th December and 1st January so is something like this
if(DateTime.Now== 25thJanuary) I don't care about the year just the day, so is it possible for C# to get these days?

DateTime now = DateTime.Now;
if (now.Day == 25 && now.Month == 12)
you could check the day and the month of today like this

Easy. For checking 25th December you can do,
if(DateTime.Now.Month == 12 && DateTime.Now.Day == 25)

using System.Diagonastics;
using System.Threading.Tasks;
DateTime now = DateTime.now;
if(now.Day == 25 && now.Month == 12)
{
....................
//Put your code here
....................
}

Well you have two choose to find do is 25th December or 1st January. First is use DateTime.Now this is return not only day, is return and hours and minutes and seconds (for seconds I'm not sure).
In my example I use DateTime.Today who return Year Month and Day. and return default hour minutes and seconds.
if ((DateTime.Today.Month == 12 && DateTime.Today.Day == 25) || (DateTime.Today.Day == 1 && DateTime.Today.Month == 1))
{
// do some stuff
}
I'm not sure but for performance maybe Today is better from Now because is not check what time is now. Today is check only what date is now (If we can talking here for performance).

Related

Birthday dosen't appear on frm_Load

When I try to letting af Label tell me, about a birthday, on a specific date, as set in the code, it does not appear. It still just response with (No birthday).
Can anyone see, what i have done wrong?
DateTime bday = Convert.ToDateTime("05-03-2019");
int years = DateTime.Now.Year - bday.Year;
bday = bday.AddYears(years);
DateTime check = DateTime.Now.AddDays(0);
if ((bday > DateTime.Now) && (bday<check))
{
lblFødselsdag.Text = ("You have birthday");
}
else
{
lblFødselsdag.Text = ("No birthday");
}
The DateTime.Now.AddDays(0), is just made for, if I want later, to let it give me the info a week before.
Thanks
bday > DateTime.Now is false since DateTime.Now includes the time of day whereas bday doesn't.
"05-03-2019" is being parsed as May 3rd instead of March 5th.
Try this:
DateTime bday = Convert.ToDateTime("03-05-2019");
int years = DateTime.Now.Year - bday.Year;
bday = bday.AddYears(years);
DateTime check = DateTime.Now.AddDays(0);
if ((bday >= DateTime.Now.Date) && (bday<check))
{
lblFødselsdag.Text = ("You have birthday");
}
else
{
lblFødselsdag.Text = ("No birthday");
}
Or simply compare year and month as suggested by #bassfader:
if (DateTime.Now.Day == bday.Day && DateTime.Now.Month == bday.Month) { ... }
If you add 0 days your "if" looks like this:
if(bday>now && bday<now)
this "if" will always be false.
The first expression disqualifies the second one.

Get DateTime of the next nth day of the month

If given a date and a variable n, how can I calculate the DateTime for which the day of the month will be the nth Date?
For example, Today is the 17th of June.
I would like a function that when provided 15 would return the DateTime for July 15.
A few more examples:
Today is Feb. 26: Function would return March 30 when provided 30.
Today is Dec. 28. Function would return Jan 4 when provided 4.
Today is Feb. 28. Function would return March 29 when provided 29, unless it was a leap year, in which case it would return Feb 29.
Why not just do?
private DateTime GetNextDate(DateTime dt, int DesiredDay)
{
if (DesiredDay >= 1 && DesiredDay <= 31)
{
do
{
dt = dt.AddDays(1);
} while (dt.Day != DesiredDay);
return dt.Date;
}
else
{
throw new ArgumentOutOfRangeException();
}
}
After many, many edits, corrections and re-writes, here is my final answer:
The method that follows returns a a DateTime representing the next time the day of number day comes up in the calendar. It does so using an iterative approach, and is written in the form of an extension method for DateTime objects, and thus isn't bound to today's date but will work with any date.
The code executes the following steps to get the desired result:
Ensure that the day number provided is valid (greater than zero and smaller than 32).
Enter into a while loop that keeps going forever (until we break).
Check if cDate's month works (the day must not have passed, and the month must have enough days in it).
If so, return.
If not, increase the month by one, set the day to one, set includeToday to true so that the first day of the new month is included, and execute the loop again.
The code:
static DateTime GetNextDate3(this DateTime cDate, int day, bool includeToday = false)
{
// Make sure provided day is valid
if (day > 0 && day <= 31)
{
while (true)
{
// See if day has passed in current month or is not contained in it at all
if ((includeToday && day > cDate.Day || (includeToday && day >= cDate.Day)) && day <= DateTime.DaysInMonth(cDate.Year, cDate.Month))
{
// If so, break and return
break;
}
// Advance month by one and set day to one
// FIXED BUG HERE (note the order of the two calls)
cDate = cDate.AddDays(1 - cDate.Day).AddMonths(1);
// Set includeToday to true so that the first of every month is taken into account
includeToday = true;
}
// Return if the cDate's month contains day and it hasn't passed
return new DateTime(cDate.Year, cDate.Month, day);
}
// Day provided wasn't a valid one
throw new ArgumentOutOfRangeException("day", "Day isn't valid");
}
The spec is a little bit unclear about to do when today is the dayOfMonth. I assumed it was it to return the same. Otherwise it would just be to change to <= today.Day
public DateTime FindNextDate(int dayOfMonth, DateTime today)
{
var nextMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1);
if(dayOfMonth < today.Day){
nextMonth = nextMonth.AddMonths(1);
}
while(nextMonth.AddDays(-1).Day < dayOfMonth){
nextMonth = nextMonth.AddMonths(1);
}
var month = nextMonth.AddMonths(-1);
return new DateTime(month.Year, month.Month, dayOfMonth);
}
Stumbled upon this thread today while trying to figure out this same problem.
From my testing, the following seems to work well and the loop only needs two goes (I think? Maybe 3 max(?)) to get to the answer:
public static DateTime GetNearestSpecificDay(DateTime start, int dayNum)
{
if (dayNum >= 1 && dayNum <= 31)
{
DateTime result = start;
while (result.Day != dayNum)
result = dayNum > result.Day ? result.AddDays(dayNum - result.Day) : new DateTime(result.Month == 12 ? result.Year + 1 : result.Year, (result.Month % 12) + 1, 1);
return result;
}
else
return DateTime.Today;
}
Edit: As requested, here's a less compact version that walks through the logic step by step. I've also updated the original code to account for a required year change when we reach December.
public static DateTime GetNearestSpecificDay(DateTime start, int dayNum)
{
// Check if target day is valid in the Gregorian calendar
if (dayNum >= 1 && dayNum <= 31)
{
// Declare a variable which will hold our result & temporary results
DateTime result = start;
// While the current result's day is not the desired day
while (result.Day != dayNum)
{
// If the desired day is greater than the current day
if (dayNum > result.Day)
{
// Add the difference to try and skip to the target day (if we can, if the current month does not have enough days, we will be pushed into the next month and repeat)
result = result.AddDays(dayNum - result.Day);
}
// Else, get the first day of the next month, then try the first step again (which should get us where we want to be)
else
{
// If the desired day is less than the current result day, it means our result day must be in the next month (it obviously can't be in the current)
// Get the next month by adding 1 to the current month mod 12 (so when we hit december, we go to january instead of trying to use a not real 13th month)
// If result.Month is November, 11%12 = 11; 11 + 1 = 12, which rolls us into December
// If result.Month is December, 12%12 = 0; 0 + 1 = 1, which rolls us into January
var month = (result.Month % 12) + 1;
// Get current/next year.
// Since we are adding 1 to the current month, we can assume if the previous month was 12 that we must be entering into January of next year
// Another way to do this would be to check if the new month is 1. It accomplishes the same thing but I chose 12 since it doesn't require an extra variable in the original code.
// Below can be translated as "If last result month is 12, use current year + 1, else, use current year"
var year = result.Month == 12 ? result.Year + 1 : result.Year;
// Set result to the start of the next month in the current/next year
result = new DateTime(year, month, 1);
}
}
// Return result
return result;
}
else
// If our desired day is invalid, just return Today. This can be an exception or something as well, just using Today fit my use case better.
return DateTime.Today;
}
Fun little puzzle. I generated 100 DateTimes which represent the starting day of each month, then checked each month to see if it had the date we want. It's lazy so we stop when we find a good one.
public DateTime FindNextDate(int dayOfMonth, DateTime today)
{
DateTime yesterday = today.AddDays(-1);
DateTime currentMonthStart = new DateTime(today.Year, today.Month, 1);
var query = Enumerable.Range(0, 100)
.Select(i => currentMonthStart.AddMonths(i))
.Select(monthStart => MakeDateOrDefault(
monthStart.Year, monthStart.Month, dayOfMonth,
yesterday)
.Where(date => today <= date)
.Take(1);
List<DateTime> results = query.ToList();
if (!results.Any())
{
throw new ArgumentOutOfRangeException(nameof(dayOfMonth))
}
return results.Single();
}
public DateTime MakeDateOrDefault(
int year, int month, int dayOfMonth,
DateTime defaultDate)
{
try
{
return new DateTime(year, month, dayOfMonth);
}
catch
{
return defaultDate;
}
}

Getting records upon Financial year 6th April to 5th April using C# and Linq

I have a table in which i have Transaction date and i want to get records from last financial year.
for ex. If today is 17-03-2017 i want to get records from 06-04-2017 to till today. then if my today's date is more than 6th April then get records from this year 06-04-2017 to till today.
How can i get records using c# and linq with this condition.?
I have used this linq query
List<TransactionMaster> donations =
db.TransactionMasters.Where(s => s.DonorId == DonorId &&
s.TransactionDate.Year >= DateTime.Now.Year - 1 &&
s.TransactionDate.Month >= 4 && s.TransactionDate.Day >= 6)
.ToList();
but i get records from only year 2016 and month > April.
So how can i get records for financial year 6th April to 5th April?
Try to compare the dates directly instead of parts, such that:
var date = new DateTime(DateTime.Now.Year, 4,6);
List<TransactionMaster> donations =
db.TransactionMasters.Where(s => s.DonorId == DonorId &&
s.TransactionDate >= date).ToList();

How can I do universal query for date range?

I'm using LINQ for getting list of objects which are in a specific date range. For example, I have current day in DateTime format: 21.05.2016 0:00:00 and I need to get news which were published after 1 day ago (5 day ago, 3 months ago, 1 year ago, 5 years ago) and until this moment. I did it the folowing way:
List<MyObject> data =
DataDownloader.myList.Where(s => s.Date.Year >= fromDate.Year
&& s.Date.Month >= fromDate.Month
&& s.Date.Day >= fromDate.Day
&& s.Date.Year <= toDate.Year
&& s.Date.Month <= toDate.Month
&& s.Date.Day <= toDate.Day).ToList();
toDate is my current date. I find the fromDate by the following:
1 day:
fromDate = toDate;
5 days:
fromDate = toDate.AddDays(-5);
3 months:
fromDate = toDate.AddMonths(-3);
etc.
But I get only 2 news for 3 months. It's 21.04.2016 0:00:00 and 21.05.2016 0:00:00. So you know they differ only numbers of months because my current date is 21.05.2016. What's I do wrong? I should get much more news I know it.
You're comparing each of the elements of a date, which isn't going to give you the right answer.
You're saying for the 'last 3 months' (from 21/02/2016 to 21/05/2016) that the day has to be between 21 and 21, the month between 2 and 5 and the year between 2016 and 2016
You're effectively searching for 21/02/2016, 21/03/2016, 21/04/2016 or 21/05/2016 rather than all dates between.
Just compare the date:
list.Where(x => x.Date >= fromDate && x.Date <= toDate).ToList();

How to check if a day is a certain date in asp.net c#.net

I would like to check, if a rendered day in a webcalendar-element is X-mas Eve or the first of January or another date of a year and if so, colour that date differently.
So if the day rendered is the third Monday in May, colour it differently. If it is X-mas eve, colour it differently and so forth.
All ive found so far is how to extract the day to a specific date. But I would like to do kinda the opposite. Has anyone done that and can offer some tips?
It's not really clear what you mean by "do kinda the opposite" but:
static IsThirdMondayInMay(DateTime date)
{
// The first X in a month is always in the range [1, 8)
// The second X in a month is always in the range [8, 15)
// The third X in a month is always in the range [15, 22)
return date.Month == 5 && date.DayOfWeek == DayOfWeek.Monday &&
date.Day >= 15 && date.Day < 22;
}
static IsChristmasEve(DateTime date)
{
return date.Month == 12 && date.Day == 24;
}
Or more generally for the last:
static MonthDayMatches(DateTime date, int month, int day)
{
return date.Month == month && date.Day == day;
}
then:
bool christmasEve = MonthDayMatches(date, 12, 24);
I assume you are using the ASP.NET Calendar control. Then use the DayRender event. This has an argument Day with a property Date which is the DateTime. Now you can use this date to decide whether it is a special day or not.
void DayRender(Object source, DayRenderEventArgs e)
{
DateTime date = e.Day.Date; // here it is
if(IsSpecialDay(date)) // your method to determine if a given date is a "special"-date
e.Cell.BackColor = System.Drawing.Color.Gold; // or use the Style property to use CSS
}

Categories

Resources