I'm trying to Get the First and Last Day of 4 Weeks based on the given Date.
For Example:
If the given Date is 8-Jan-2023 then the week start and end should be 1-Jan-2023 and 28-Jan-2023 respectively.
If the given Date is 10-Jan-2023 then the week start and end should be 1-Jan-2023 and 28-Jan-2023 respectively.
If the given Date is 30-Jan-2023 then the week start and end should be 29-Jan-2023 and 25-Jan-2023 respectively.
Basically, the use case depends on the very first input. If the first input is 15-Jan then the first 4 weeks are recorded in the database as 15-Jan to 11-Feb. In that case, 17-Jan belongs to that week
How to do this?
I'm getting the Start Day & end Date of the week as below:
public static DateTime FirstDayOfWeek(this DateTime dt)
{
var culture = Thread.CurrentThread.CurrentCulture;
var diff = dt.DayOfWeek - culture.DateTimeFormat.FirstDayOfWeek;
if (diff < 0)
{
diff += 7;
}
return dt.AddDays(-diff).Date;
}
public static DateTime LastDayOfFourWeeks(this DateTime dt) =>
dt.FirstDayOfWeek().AddDays(27);
Related
I run into this question of how to determine if DateTime.UtcNow (e.g. 2018-01-01T20:00:00Z) falls within the given range of days and times that are in another timezone. There are no specific dates given, just the days of the week, and the time of the day. The given time is in ISO 8601 standard format.
To simplify this question, it can be how to check if a UTC time is within business hours in China.
For example, the given day and time range is given by someone form China in time zone +08:00, it can be: FromDayOfWeek = "Friday", FromTimeOfDay = "17:00:00+8:00", ToDayOfWeek = "Monday", ToTimeOfWeek = "08:00:00+8:00". I need to determine if "now" in China is sometime between the given range (Friday 17:00:00+8:00 - Monday 08:00:00+8:00).
I'm stuck at how to convert the DateTime and get the day of the week in that local time, since 2018-01-01T20:00:00Z is Monday in UK, but at the same time, since China is +08:00, it is already Tuesday in China.
My approach:
// parse the time to get the zone first (+08:00)
TimeSpan ts = TimeSpan.Parse("-08:00");
// Create a custom time zone since the time zone id is not given, and cannot be searched by SearchTimeZoneById
TimeZoneInfo tzi = TimeZoneInfo.CreateCustomTimeZone(zoneId, ts, displayName, standardName);
DateTime localDateTime = TimeZoneInfo.ConvertTime(Date.UtcNow, tzi);
String localDay = localDateTime.DayOfWeek;
// Determine if localDay is between FromDayOfWeek and ToDayOfWeek
// cast the days to integers from 1 (Monday) to 7 (Sunday)
// create an array of days in integar days = [5, 6, 7, 1]
// if days.contains(localDays), check the times
...
Can anyone suggest some better solutions? I am not sure if mine works, and there are holes in how to deal with Day Light Saving time, since the zone will change, and how to check the time range. I am new to C#, any suggestions of libraries I can use is great!
Instead of converting both start and end times from UTC, just convert the other time into UTC
TimeZoneInfo chinaTimeZone = TimeZoneInfo.CreateCustomTimeZone(zoneID, TimeSpan.Parse("-08:00"), displayName, standardName);
DateTime FromTime = new DateTime(2018, 0, 19, 13, 0, 0); // year, month, day, hour, minute, second : Friday 1pm
DateTime ToTime = new DateTime(2018, 0, 21, 1, 0, 0); // year, month, day, hour, minute, second : Monday 1am
DateTime nowinUTC = DateTime.UtcNow;
DateTime nowInChina = TimeZoneInfo.ConvertTimeFromUtc(nowinUTC, chinaTimeZone);
if(FromTime< nowInChina && ToTime> nowInChina)
{
// Time is within the from and two times
}
Per the comments on #Moffen's answer, you only want to check if Now is within a specific DayOfWeek range:
public void CheckAll(List<SomeClass> spans)
{
var chinaTZ = TimeZoneInfo.CreateCustomTimeZone(zoneID, TimeSpan.Parse("-08:00"), displayName, standardName);
var nowInChina = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, chinaTZ);
foreach ( var span in spans )
{
if (InRange(nowInChina, span.startDay, span.endDay))
// Do something on success
// Check for valid times here
;
else
// Do something on Failure
;
}
}
public bool InRange(DateTime dateToCheck, DayOfWeek startDay, DayOfWeek endDay)
{
// Initialise as one day prior because first action in loop is to increment current
var current = (int)startDay - 1;
do
{
// Move to next day, wrap back to Sunday if went past Saturday
current = (current + 1) % 7;
if (dateToCheck.DayOfWeek == (DayOfWeek)current)
return true;
} while (current != (int)endDay);
return false;
}
I am trying to add a month to a date and populate textboxes based on the previous month. For months that end on the 31st (and even February 28th) this works. But, if the previous month ended on the 30th and the next month ends on the 31st, it is either one day short or one day long. For example:
Previous start date: 4/1/2017
Previous end date: 4/30/2017
New start date: 5/1/2017
New end date: SHOULD BE 5/31/2017
Here is the code I have:
// Set the Start Date
DateTime dtNewStartDate;
dtNewStartDate = Convert.ToDateTime(txtRecentBeginDate.Text).AddMonths(1);
txtNewStartDate.Text = dtNewStartDate.ToString();
// Set the End Date
DateTime dtNewEndDate;
dtNewEndDate = Convert.ToDateTime(txtNewStartDate.Text).AddMonths(1);
txtNewEndDate.Text = dtNewEndDate.ToString();
This produces an end date of 6/1/2017 instead of 5/31/2017
EDIT: I was able to find what I was looking for from https://social.msdn.microsoft.com/Forums/en-US/218260ec-b610-4fa6-9d1b-f56f3438b721/how-to-get-the-last-day-of-a-particular-month?forum=Vsexpressvcs.
This solution accounts for leap years and getting the correct last day of the month for any circumstance. This is what I came up with:
// Set the End Date
int intYear = dtNewStartDate.Year;
int intMonth = dtNewStartDate.Month;
int intNumberOfDays = DateTime.DaysInMonth(intYear, intMonth);
DateTime dtNewEndDate = new DateTime(intYear, intMonth, intNumberOfDays);
txtNewEndDate.Text = dtNewEndDate.ToString();
You can just get the last day of the month for that month.
DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year,
today.Month,
DateTime.DaysInMonth(today.Year,
today.Month));
This is what I typically do: Just take the year and month from the start date, create a new date based on that, add a month and subtract a day which ends up being the last day of the next month::
DateTime dtNewEndDate = new DateTime(dtNewStartDate.Year, dtNewStartDate.Month, 1)
.AddMonths(1)
.AddDays(-1);
I have something odd requirement. I have Current Date and List of Week Days. And I want next all possible date till the target date.
For i.e. Today, its 22-04-2014 And Tuesday. Target date is 15-05-2014I have 2 week days, Monday and Thursday. So code should find near by Week Day, which will be Thursday here. So It should return date of Thursday which is 24-04-2014. Now, next turn is of Monday which comes from List. So now, It should return date of Monday which is 28-04-2014.
It should keep repeating till the target date.
So, final result will be
24-04-2014,
28-04-2014,
1-05-2014,
5-05-2014,
8-05-2014,
12-05-2014
Please help me to get this type of result. Here, Monday and Thursday is not fixed. It can be any Day and any number of Day.
Update : Link to the working example - Example
You can try this code, i have tested it and working correctly
private List<DateTime> ProcessDate(DateTime dtStartDate, DateTime targetDate)
{
DateTime dtLoop = dtStartDate;
//dtRequiredDates to hold required dates
List<DateTime> dtRequiredDates = new List<DateTime>();
for (int i = dtStartDate.DayOfYear; i < targetDate.DayOfYear; i++)
{
if (dtLoop.DayOfWeek == DayOfWeek.Monday || dtLoop.DayOfWeek == DayOfWeek.Thursday)
{
dtRequiredDates.Add(dtLoop);
}
dtLoop = dtLoop.AddDays(1);
}
return dtRequiredDates;
}
You may have to enhance this codes so that it doesn't throw any exception based on the requirement.
UPDATE 2:
You can have another method which will accept the days of week as follows
private List<DateTime> ProcessDate(DateTime dtStartDate, DateTime targetDate, List<DayOfWeek> daysOfWeek)
{
DateTime dtLoop = dtStartDate;
List<DateTime> dtRequiredDates = new List<DateTime>();
for (int i = dtStartDate.DayOfYear; i < targetDate.DayOfYear; i++)
{
foreach (DayOfWeek day in daysOfWeek)
{
if (dtLoop.DayOfWeek == day)
{
dtRequiredDates.Add(dtLoop);
}
}
dtLoop = dtLoop.AddDays(1);
}
return dtRequiredDates;
}
Here is the Example
Hence you can pass any number of week days as you wish.
Hope this helps
You could try something like this:
List<DayOfWeek> listOfDays = new List<DayOfWeek>{DayOfWeek.Monday, DayOfWeek.Thursday};
var end = new DateTime(2014,05,15);
var day = DateTime.Now.Date;
while (day < end)
{
day.AddDays(1); // adds +1 days to "day"
if (listOfDays.Contains(day.DayOfWeek)) Console.WriteLine(day.Date.ToString());
}
(I can't test the code right now, so maybe you need to modify a little ;-)
user just enter the day of week. For instance user enter friday. I need to find the exact date of given day and format will be like dd.MM.yyyy.
But I don't know how I do it.
Example:
label1 - Friday (entered by user)
label2 - 08.06.2012 (found by system)
label1 is just a string (just Friday). It's coming from webservice as a string variable. I need to find the date and compare with today, If it's not equal or small than today I give date of upcoming Friday, else I give the date of the Friday the week after.
"If it's not equal or small than today I give exact date, else I give next week date. "
Assuming that means that you return always the next date in future with the given day of week, the only exception is when today is the given day of week.
public static DateTime getNextWeekDaysDate(String englWeekDate)
{
var desired = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), englWeekDate);
var current = DateTime.Today.DayOfWeek;
int c = (int)current;
int d = (int)desired;
int n = (7 - c + d);
return DateTime.Today.AddDays((n >= 7) ? n % 7 : n);
}
Let's test:
DateTime Monday = getNextWeekDaysDate("Monday"); // 2012-06-11
DateTime Tuesday = getNextWeekDaysDate("Tuesday"); // 2012-06-05 <-- !!! today
DateTime Wednesday= getNextWeekDaysDate("Wednesday"); // 2012-06-06
DateTime Thursday = getNextWeekDaysDate("Thursday"); // 2012-06-07
DateTime Friday = getNextWeekDaysDate("Friday"); // 2012-06-08
Create enum of days (i.e. monday - 0, tuesday - 1, etc);
Get DateTime.Now DayOfWeek and cast in some way it to your enum value.
Calculate difference between Now.DayOfWeek and user's day of the week;
Use DateTime.AddDays(difference).DayofTheWeek;
get current time with DateTime.now
Current day is DateTime.Now.DayOfWeek
Then get the day of week your user entered
Then your result is DateTime.now.AddDays( NowDayOfWeek - UserDayOfWeek).
We have a unique requirment where we have our own start day of a week and end day of a week(C#),
Contrary to the existing Date Time class whose start day is Sunday and end day is Saturday, we have Wednesday as our start day and Tuesday our EndDay (and this will vary per client).
and we need to implement the following logic
a) for a given date get the start Date of a week and end Date of a week
Ex: based on the above if the current day is 23/Sep/2010 (Thur) we need to get 22/Sep/2010 (Wed) as our Start Day and 28/Sep/2010 (Tue) as our end day
i apologize there is a correction the end day should be Tuesday (7 days a week)
Can anyone help here?
Thanks
Couldn't you just do
(dt.DayOfWeek + delta) % 7
?
Here is my inelegant crack at it:
public static void CalculateWeek (out DateTime WeekStart, out DateTime WeekEnd, DateTime InputDate)
{
DateTime tempDT = InputDate;
while (tempDT.DayOfWeek != DayOfWeek.Wednesday)
{
tempDT = tempDT.AddDays(-1);
}
WeekStart = tempDT.Date;
while (tempDT.DayOfWeek != DayOfWeek.Tuesday)
{
tempDT = tempDT.AddDays(1);
}
WeekEnd = tempDT.Date;
}
By no means clever or superefficient, although the loops will iterate no more than a trivial 7 times.