Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
The user has a subscription, for example, for 12 lessons per month. On Mondays, Tuesdays, Wednesdays. How to calculate when the subscription ends and enter the dates in the database when a person will have training. That is, this is not one end date of the subscription, this is a set of dates on which days a person will have training in the gym. In this case, you can specify different days on which there will be training and their count. For example, 6 workouts on Mondays and Wednesdays will end on 01/18/2023 if counting from today. And the dates you need to get are 01/02/2023, 01/04/2023, 01/09/2023, 01/11/2023 and so on
I don't know how to implement it
You could loop the days between the date ranges and then check if the day is (Mondays, Tuesdays, Wednesdays); if so, you have the dates you want.
Code sample:
// Start and end dates = in your case, 12 months.
DateTime start = DateTime.Today;
DateTime end = start.AddMonths(12);
// Loop the days between the start and end dates:
for (DateTime counter = start; counter <= end; counter = counter.AddDays(1))
{
// Handle the days (i.e. Monday, Tuesday, etc) :
switch (counter.DayOfWeek)
{
// If the day matches your criteria:
case DayOfWeek.Monday:
case DayOfWeek.Tuesday:
case DayOfWeek.Wednesday:
// Here is where you get the date and store it in your database:
Console.WriteLine("Day: " + counter.DayOfWeek.ToString() + " -- Date: " + counter.ToString("MM/dd/yyyy"));
break;
default:
break;
}
}
Result:
Day: Monday -- Date: 01/02/2023
Day: Tuesday -- Date: 01/03/2023
Day: Wednesday -- Date: 01/04/2023
Day: Monday -- Date: 01/09/2023
Day: Tuesday -- Date: 01/10/2023
Day: Wednesday -- Date: 01/11/2023
Day: Monday -- Date: 01/16/2023
[and so on - depending of the date ranges]
dotnetfiddle.net sample and the preview.
You need to get the 4th Wednesday based on the given DateTime.
In this case, I have used the current DateTime. but you can pass the DateTime accordingly or you can modify this method based on your requirement.
private static DateTime GetFourthWednesday(DateTime dt)
{
DateTime firstDayOfMonth = new DateTime(dt.Year, dt.Month, 1);
int count = 0;
while (count < 4)
{
if (firstDayOfMonth.DayOfWeek == DayOfWeek.Wednesday)
{
count++;
}
if (count == 4)
{
return firstDayOfMonth;
}
firstDayOfMonth = firstDayOfMonth.AddDays(1);
}
return firstDayOfMonth;
}
DateTime now = DateTime.Now;
var dt = GetFourthWednesday(now);
You can calculate dates by using DateTime.Now.AddDays(DaysInNumber) or DateTime.Now.AddMonths(MonthInNumber) etc. in C#.
Related
I was looking for a way to fetch the same day of the current week as a year ago. For example, today is:
August 10th 2022 - Wednesday.
Assume this is the check-in date, the check-out date I expect to get is:
August 11, 2021 - Wednesday.
Because it's the same day (Wednesday) as last year. But I need to take leap years into account, so I need to see if the current year is a leap year and if it is, if it has passed the 29th of February, the same with the date last year.
How to do this using .net core ? I thought of something like:
private DateTime GetDayOneYearBefore()
{
if(DateTime.IsLeapYear(DateTime.Today.Year) && DateTime.Today.Month > 2){
return DateTime.Today.AddDays(-365);
}
else if(DateTime.IsLeapYear(DateTime.Today.Year) && DateTime.Today.Month <= 2){
return DateTime.Today.AddDays(-364);
}
}
Since you mention the "same week" I suppose you want to get the same day of the week in the same week number?
If so, you can do the following:
// In the System.DayOfWeek enum Sunday = 0, while Monday = 1
// This converts DateTime.DayOfWeek to a range where Monday = 0 and Sunday = 6
static int DayOfWeek(DateTime dt)
{
const int weekStart = (int)System.DayOfWeek.Monday;
const int daysInAWeek = 7;
return (daysInAWeek - (weekStart - (int)dt.DayOfWeek)) % daysInAWeek;
}
var calendar = CultureInfo.CurrentCulture.Calendar;
var weekNum = calendar.GetWeekOfYear(DateTime.Today, CalendarWeekRule.FirstFourDayWeek, System.DayOfWeek.Monday);
var todayLastYear = DateTime.Today.AddYears(-1);
var lastYearWeekNum = calendar.GetWeekOfYear(todayLastYear, CalendarWeekRule.FirstFourDayWeek, System.DayOfWeek.Monday);
var sameWeekLastYear = todayLastYear.AddDays(7 * (weekNum - lastYearWeekNum));
var sameDaySameWeekLastYear = sameWeekLastYear.AddDays(DayOfWeek(DateTime.Today) - DayOfWeek(sameWeekLastYear));
As you might notice there's a little convertion method, since I normally work with Monday being the first day of the week. If you prefer a different day to be the first day of the week, simply replace System.DayOfWeek.Monday with which ever day you'd like.
See this fiddle for a test run.
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);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How do i go about creating a datetime based on only the following information:
Day of Week, Hour & Minuet.
I.e. I don't care what month it is or even what the date is (i don't have that info in the database).
I thought i could parse them as a string but is turning out to be more difficult than i thought.
Created on function for you it might be helpful to you ..
public DateTime CreateDayOfWeek(int DayOfWeek,int hour,int min)
{
DateTime dt = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,hour,min,0);
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilTuesday = (DayOfWeek - (int)dt.DayOfWeek + 7) % 7;
// DateTime nextTuesday = today.AddDays(daysUntilTuesday);
dt = dt.AddDays(daysUntilTuesday);
return dt;
}
I have tested for several dates and its working for me ..
let me know if you have any issue ..
Here is .netFiddle
You can create your date like this...
var hour = 1; // you set this from code
var minute = 1; // set this from code
var now = DateTime.Now;
var tempDateTime = new DateTime(now.Year, now.Month, now.Day, hour, minute, 0);
// Make this enum whatever you want your date to be...
var num = (int)DayOfWeek.Sunday;
var dateForComparison = tempDateTime.AddDays(num - (int)tempDateTime.DayOfWeek);
Now dateForComparison holds a date that has your time values set and the day of week you have specified.
You said you don't care about what month or date it is, which makes me assume you want any date as long as it is the right day of week and time (hour and minute). You can do it like this:
var date = new System.DateTime(2016, 9, 25);
date = date.AddDays(dow).AddHours(hours).AddMinutes(minutes);
September 25, 2016 was a Sunday. Add the day of the week (Sunday = 0) and you get the correct day. Then add the hours and minutes. Of course, if you like you can pick any Sunday of any month/year to start.
You can create a function for build your date:
public DateTime BuildDate(Int32 day, Int32 hour, Int32 minute)
{
var now = DateTime.Now;
var initialDate = now.AddDays(((Int32)now.DayOfWeek + 1) * -1);
return new DateTime(initialDate.Year, initialDate.Month, initialDate.AddDays(day).Day, hour, minute, 0);
}
The day of week is start from sunday in this case.
You can use: DateTime.ToString Method (String)
DateTime.Now.ToString("ddd HH:mm") // for military time (24 hour clock)
More: https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
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).
using c# visual studio 2008.
Can anyone help with an algorithm to do this please
if i have a range of days selected for this week (eg monday to friday) i can find the dates for these using the datetime functions available.
What i want to do is compared to stored data for the same DAY range 1 year ago.
So basicly i need to go back 1 year and find the dates for the nearest Mon to fri DAY range from 1 year previous. I guess i also need to take into acount leap years.
Can anyone help with a suitable algorithm on how to achieve this.
Of course the DAY for todays date last year is not going to be the same day.
thanks in advance
Here's some code which might do what you want - but the test cases show that there are corner cases to consider:
using System;
public class Test
{
static void Main()
{
Console.WriteLine(SameDayLastYear(DateTime.Today));
Console.WriteLine(SameDayLastYear(new DateTime(2010, 12, 31)));
}
static DateTime SameDayLastYear(DateTime original)
{
DateTime sameDate = original.AddYears(-1);
int daysDiff = original.DayOfWeek - sameDate.DayOfWeek;
return sameDate.AddDays(daysDiff);
}
}
What would you want the result for the second call to be? This code returns January 1st 2010, because that's the closest date to "a year ago on the same day".
I strongly suggest that whatever you go with, you have unit tests checking leap years, start and end of year etc.
Let's say you select Wednesday 10-02-2010 - Friday 12-02-2010 this year.
Last year that would have been Tuesday 10-02-2009 - Thursday 12-02-2009.
So you can do the following: Go back a year by simply performing DateTime.AddYears(-1). Make sure you correct for leap years here.
Then you use .AddDays(1) until you end up on a Wednesday - Friday timeframe.
That way you only have to take leap years into account at one point and this should produce the result you need.
I just subtracted one year then ran backwards until I found a Monday. LastYear will end up being the first Monday before this date last year
DateTime LastYear = DateTime.Now.AddYears(-1)
DayOfWeek Check = LastYear.DayOfWeek;
while (Check != DayOfWeek.Monday)
{
LastYear = LastYear.addDays(-1);
Check = LastYear.DayOfWeek;
}
Console.WriteLine("{0}",LastYear);
DateTime now = DateTime.Now;
DateTime lastyear = now.AddYears(-1);
string dayOfWeek = lastyear.DayOfWeek.ToString();
if (dayOfWeek.Equals("Saturday")) { dayOfWeek = "Friday"; }
else if (dayOfWeek.Equals("Sunday")) { dayOfWeek = "Monday"; }
Console.WriteLine(dayOfWeek);
Console.ReadKey();
Get a datetime object for last year, then use the DayOfWeek property.
This was pretty fun.
// today's info
DateTime today = DateTime.Now;
DayOfWeek today_name = today.DayOfWeek;
// this day one year ago
DateTime year_ago = today - new TimeSpan( ((today.Year - 1) % 4) ? 365 : 366, 0, 0, 0);
// find the closest day to today's info's name
DayOfWeek today_name_a_year_ago = year_ago.DayOfWeek;
DateTime current_range_a_year_ago = year_ago - new TimeSpan( year_ago.DayOfWeek - today_name, 0, 0, 0);
Console.WriteLine( "Today is {0}, {1}", today_name, today);
Console.WriteLine( "One year from today was {0}, {1}", today_name_a_year_ago, year_ago);
Console.WriteLine( "New date range is {0}", current_range_a_year_ago);
I would highly recommend using the unit testing features built into VS2008 to make sure you account for corner cases.