c# datetime create Day of Week Hour and Min [closed] - c#

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

Related

How to select the dates depending on the number [closed]

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#.

Subtract specific hours and days from a TimeSpan [closed]

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 3 months ago.
Improve this question
I want to calculate the time in hours and minutes between two dates. But also subtract certain hours and dates in that period.
Example:
DateTime startDate = new DateTime(2022,10,8,14,35,1)
DateTime endDate = new DateTime(2022,11,1,17,46,62)
With:
Timespan ts = endDate.Subtract(starDate);
I get the whole timespan between the dates.
But I want to subtract all the time between:
00:OO - 08:00 on all days
19:00 - 24:00 on all days
00:00 — 24:00 Saturdays and Sundays
00:00 - 24:00 on specific dates
I can get the correct results for this but not very efficient.
Pseudo code:
int seconds = 0
while(startDate <= endDate)
{
if(startDate not in excludedTime)
seconds++;
startDate = startDate.AddSeconds(1);
}
There must be a more efficent way of doing this?
One idea is to write one method that will adjust a date based on the weekend/holiday rules, another to get the timespan from a day based on the working hour rules, and then a third that utilizes these to add up the timespans for each day in a range.
For the first method, I've added a bool forward argument that we can set to false for adjusting the end date, since presumably the implementation of moving a date backwards is slightly different. Note that when moving a day to a new day, I use the .Date property of the result to reset the time information:
public static DateTime AdjustDate(DateTime input, bool forward = true)
{
var skipDates = new List<DateTime>
{
// add a comma-separated list of dates to skip here
};
while (skipDates.Contains(input.Date))
input = input.AddDays(forward ? 1 : -1).Date;
if (input.DayOfWeek == DayOfWeek.Saturday)
input = input.AddDays(forward ? 2 : -1).Date;
if (input.DayOfWeek == DayOfWeek.Sunday)
input = input.AddDays(forward ? 1 : -2).Date;
return input;
}
Once we have that method working, we need one that will get us the timespan for just the specific working hours of that day. Once again we have a bool argument that specifies if we're counting hours FROM the start of the day or TO the end of the day. Then we can add logic to adjust the actual hour of the date and do our math based on the specified start and end hours for a day.
public static TimeSpan GetNetTimeSpan(DateTime input, bool fromStart = true)
{
if (input.Hour > 19)
{
if (fromStart)
input = new DateTime(input.Year, input.Month, input.Day, 19, 0, 0);
else return TimeSpan.Zero;
}
if (input.Hour < 8)
{
if (fromStart) return TimeSpan.Zero;
else input = new DateTime(input.Year, input.Month, input.Day, 8, 0, 0);
}
if (fromStart)
{
return input - new DateTime(input.Year, input.Month, input.Day, 8, 0, 0);
}
else
{
return new DateTime(input.Year, input.Month, input.Day, 19, 0, 0) - input;
}
}
With these in place, we should now be able to loop through all the days and create a timespan that encapsulates the valid ticks of each day:
public static TimeSpan GetNetDifference(DateTime start, DateTime end)
{
// First, adjust our start and end dates to avoid weekends and holidays
start = AdjustDate(start);
end = AdjustDate(end, false);
// If our start is no longer less than our end, return zero
if (start >= end) return TimeSpan.Zero;
// Begin with the start date timespan
var result = GetNetTimeSpan(start);
// Next loop through each day between start and end and add them to the result
var current = AdjustDate(start.AddDays(1).Date);
while(current.Date < end.Date)
{
result += GetNetTimeSpan(current);
current = AdjustDate(current.AddDays(1).Date);
}
// Add our last day and return the result
return result + GetNetTimeSpan(end);
}
I haven't tested it, partly because it's not completely clear if this follows your rules, but it should give you a good starting point.
Also, it would be more flexible if we parameterized the start and end times rather than having them hard-coded at 8 and 19.

How can we get Monthly(Day-Of-Week) for backup purpose [duplicate]

This question already has answers here:
Get DateTime of the next nth day of the month
(5 answers)
How to calculate 2nd Friday of Month in C# [duplicate]
(4 answers)
Closed 3 years ago.
I want to get a next backup date using (day-of-week) monthly for a scheduled backup.
If I took a backup on Monday, second week, Jan-2019, then Next backup date should be Monday in the second week of February-2019.
So, How can we get the specific day as per the given week for every coming month?
Now I'm getting the next backup month but I'm not sure how we get the same Day in a specfic week.
You should create an extension method for DateTime class.
public static DateTime NthOf(this DateTime CurDate, int Occurrence , DayOfWeek Day)
{
var fday = new DateTime(CurDate.Year, CurDate.Month, 1);
var fOc = fday.DayOfWeek == Day ? fday : fday.AddDays(Day - fday.DayOfWeek);
if (fOc.Month < CurDate.Month) Occurrence = Occurrence+1;
return fOc.AddDays(7 * (Occurrence - 1));
}
And use
new DateTime().NthOf(2, DayOfWeek.Monday))
Refer: How to calculate 2nd Friday of Month in C#
Why dont you get the DayOfTheYear and just add 7 to it. Something like this:
var dateTime = DateTime.Now;
var dayOfYear = dateTime.DayOfYear;
var nextDate = dateTime.AddDays(dayOfYear + 7);
Console.WriteLine(nextDate);
Since the next backup day is the same day, which means just add 7 to it. You will have to manage the last week of year though in this case

How to get the first and last day of a month calendar view (sunday-saturday)

I have a calendar that's first week day starts in Sunday and ends in Saturday.
Right now I can only disable days in the calendar current month because I don't know the first and last day in the calendar.
The code that Im using is pretty simple right now:
private List<DateTime> GetDisabledDates(DateTime fromDate, DateTime toDate){
// right now fromDate and toDate are the start and end days in a month
var disabledDates = SearchDates(fromDate, toDate);
return disabledDates;
}
So, what I need is to get the first day and last day showed in the calendar month, considering that week starts in Sunday and ends in Saturday.
Any clue on how to dinamically get first and last (yellow marked dates) from a specific month? Considering the calendar configuration?
Well for the first day in this view something like this should do it
//Using UTC to counter daylight saving problems
var month = new DateTime(2014, 8, 1, 0, 0, 0, DateTimeKind.Utc);
var firstInView = month.Subtract(TimeSpan.FromDays((int) month.DayOfWeek));
For the remaining days you just need to calculate the amount left in (7 * NumRows) - (DaysOfCurrentMonth + DaysOfPreviousMonth), where DaysOfPreviousMonth is the DayOfWeek property of this month first day again.
The solution that works for me:
int totalCalendarDays = 42; // matrix 7 x 6
// set the first month day
DateTime firstDayMonth = new DateTime(date.Year, date.Month, 1);
// set the lastmonth day
DateTime lastDayMonth = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));
// now get the first day week of the first day month (0-6 Sun-Sat)
byte firstDayWeek = (byte) firstDayMonth.DayOfWeek;
// now get the first day week of the last day month (0-6 Sun-Sat)
byte lastDayWeek = (byte) lastDayMonth.DayOfWeek;
// now the first day show in calendar is the first day month minus the days to 0 (sunday)
DateTime firstDayCalendar = firstDayMonth.Subtract(TimeSpan.FromDays(firstDayWeek));
int tempDays = (lastDayMonth - firstDayCalendar).Days;
DateTime lastDayCalendar = lastDayMonth.Add(TimeSpan.FromDays(totalCalendarDays - tempDays - 1));
Maybe is a better way to do this :)
Here´s my suggestion, defining year and month as parameters:
public DateTime[] GetMonthDisplayLimits(int year, int month)
{
int lastDay = DateTime.DaysInMonth(year, month);
var firstDayInMonth = new DateTime(year, month, 1);
var lastDayInMonth = new DateTime(year, month, lastDay);
var firstDayInView = firstDayInMonth.AddDays(-1 * (int) firstDayInMonth.DayOfWeek);
var lastDayInView = lastDayInMonth.AddDays((int) (6 - lastDayInMonth.DayOfWeek));
return new DateTime[] { firstDayInView, lastDayInView };
}
DateTime[] monthDisplayLimits = GetMonthDisplayLimits(2014, 8);
var firstDayInView = monthDisplayLimits[0];
var lastDayInView = monthDisplayLimits[1];
Since "DayOfWeek" is a value between 0 and 6, this approach rounds down the first weekday and rounds up the last weekday.

Check Date Equals 1st Date of Month C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
User can input any date, month and year like 12/12/2013, 1/1/2014, 7/5/2014, 5/1/2012 in MM\DD\YYYY format.
How to check the date is first date of month ?
If the user entry is not first date of month, I want to modify that entry to 1st date of month. In my Examples, I want
12/12/2013 as 12/1/2013
1/1/2014 as 1/1/2014(No Change)
7/5/2014 as 7/1/2014
5/1/2012 as 5/1/2012(No Change)
Thanks
DateTime date = ... // your original date here...
// Don't bother checking, just create a new date for the 1st.
date = new DateTime(date.Year, date.Month, 1);
UPDATE:
The OP has apparently changed the specs:
DateTime date = ... // your original date here...
if (date.Day != 1)
date = new DateTime(date.Year, date.Month, 1).AddMonths(1);
(let the .AddMonths() method worry about the year rolling over in December...)
IMO, since you have a definite format you expect from users (MM\DD\YYYY) why not do a simple split and dig your hit:
string arbitDate = "4/3/2014";
string UsersFirstDay = arbitDate.Trim().Split(new String[] { "/" }, StringSplitOptions.RemoveEmptyEntries)[1].Trim();//index 1 is the DD part - according to your format
UsersFirstDay = (UsersFirstDay == "1") ? UsersFirstDay : "1";
Pass your date to this function:
public static void ConvertToFirstDate(ref DateTime dt){
TimeSpan ts = dt.Subtract(new DateTime(dt.Year, dt.Month, 1));
dt = dt.AddDays(-ts.Days);
}

Categories