How do I loop the whole week (monday-sunday) based on culture info, so in my case monday will be the first day of the week? And is it possible to find the int value of the day at the same time?
For some information: I need to make this in order to make some generel opening hours for a store.
I think what you need is the following loop.
DayOfWeek firstDay = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
for (int dayIndex = 0; dayIndex < 7; dayIndex++)
{
var currentDay = (DayOfWeek) (((int) firstDay + dayIndex) % 7);
// Output the day
Console.WriteLine(dayIndex + " " + currentDay);
}
The modulo 7 is important, because the firstdayofweek can vary by different cultures.
This would give you the first day of the week in a given culture.
DayOfWeek firstDay = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
this could subsequently be...
int firstDay = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
DayOfWeek.Sunday = zero
DayOfWeek.Saturday = 6
You would iterate it like any other int.
http://msdn.microsoft.com/en-us/library/system.dayofweek.aspx
DateTime Dt = new DateTime(2011,5,13,0,0,0);
int WeeklyOffValue = (int)Dt.DayOfWeek
The Time Period Library for .NET includes the class Week with support of the culture:
// ----------------------------------------------------------------------
public void WeekDaysSample()
{
Week week = new Week( new DateTime( 2011, 05, 13 ) );
foreach ( Day day in week.GetDays() )
{
Console.WriteLine( "Day: {0}, DayOfWeek: {1}, Int: {2}", day, day.DayOfWeek, (int)day.DayOfWeek );
// > Day: Montag; 09.05.2011 | 0.23:59, DayOfWeek: Monday, Int: 1
// > Day: Dienstag; 10.05.2011 | 0.23:59, DayOfWeek: Tuesday, Int: 2
// > Day: Mittwoch; 11.05.2011 | 0.23:59, DayOfWeek: Wednesday, Int: 3
// > Day: Donnerstag; 12.05.2011 | 0.23:59, DayOfWeek: Thursday, Int: 4
// > Day: Freitag; 13.05.2011 | 0.23:59, DayOfWeek: Friday, Int: 5
// > Day: Samstag; 14.05.2011 | 0.23:59, DayOfWeek: Saturday, Int: 6
// > Day: Sonntag; 15.05.2011 | 0.23:59, DayOfWeek: Sunday, Int: 0
}
} // WeekDaysSample
This works even today, Friday the 13th :)
for (int i = 1; i <= 7; i++)
Console.WriteLine(new DateTime(2014, 6, i).ToString("DDDD", culture));
July 1, 2014 - Sunday
I believe you want to loop through the weeks, something like this
foreach (DayOfWeek dy in Enum.GetValues(typeof(DayOfWeek)))
{
dy.ToString() // this would be Sunday, monday ......
}
Related
I have a Google API that takes date and time and sets up a event in customers calendar and the problem is I am using date time to add hours to the event when I boot time for 12pm noon For whatever reason, it will be listed in my Google Calendar for the day after at 12am.
Here is the code that sets up the date and the time:
// dd is a drop down for hours 1 to 12 Central Time Zone
int iHour = Convert.ToInt32(dd.SelectedItem.Text);
// and this is the minutes values of 30 or 45
int iMinute = Convert.ToInt32(ddMinute.SelectedItem.Text);
var date = "Nov 19, 2017";
DateTime dt = new DateTime();
dt = Convert.ToDateTime(date);
// If its PM set 12 hours more to it because its a 24 hours clock
if (ddAptAmPm.SelectedValue == "PM")
iHour += 12;
dt = dt.AddHours(iHour);
dt = dt.AddMinutes(iMinute);
var startDate = dt;
var endDate = dt;
string sNotes = "TestingA PI";
string sTitle = "Testas" + " with: " + "ASP.NEt" + " " + "Last Name here";
int length = Convert.ToInt32("30");
endDate = endDate.AddMinutes(length);
var google = new GoogleCalendar();
int value = google.CreateCalendarEvent("email", startDate, endDate, sNotes, sTitle);
Can any one see where did I do this wrong
if (ddAptAmPm.SelectedValue == "PM") // If its PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
should be:
if (ddAptAmPm.SelectedValue == "PM" && iHour < 12) // If its 1-11 PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
else if (ddAptAmPm.SelectedValue == "AM" && iHour == 12)
iHour = 0;
Since 12 + 12 is 24, and today plus 24 hours is the next day.
Another way to write it:
if (iHour == 12) // 12 is **before** 1
iHour = 0;
if (ddAptAmPm.SelectedValue == "PM") // If its PM set 12 hours more to it because its a 24 hours clock
iHour += 12;
Another way you could do it is to construct a date string in a specific format (including the AM or PM designation), and then use DateTime.ParseExact to create your startDate. This way you don't have to do all the conversion from string to int, then add 12 hours if PM was specified, etc.
For example, this code would replace everything you currently have up to and including the startDate assignment:
// This assumes that ddAptAmPm.SelectedValue will be "AM" or "PM"
var dateString = string.Format("Nov 19, 2017 {0}:{1} {2}", dd.SelectedItem.Text,
ddMinute.SelectedItem.Text, ddAptAmPm.SelectedValue);
// In a format string, tt is a placeholder for AM/PM
var startDate = DateTime.ParseExact(dateString, "MMM dd, yyyy h:m tt",
CultureInfo.InvariantCulture);
You can read more about Date and Time Format Strings here.
I am trying to shift a date by a number of given months, but also to keep the same day (for example, if the day of the date is Monday, and after shifting with x months the day is Thursday, I want also to subtract 3 days from the new obtained date. This algorithm should add/subtract days depending on the new obtained date, basically providing the closest date that represents the same day of week). As an example, if I have the start date 10.08.2016(Wednesday), and I add 3 months, I will get 10.11.2016(Thursday), so the closest Wednesday to that day is 09.11.2016.
What I managed to make till now looks something like this:
int startDayOfWeek = ((int)startDay.DayOfWeek) == 0 ? 7 : (int)startDay.DayOfWeek;
int newStartDayOfWeek = ((int)startDay.AddMonths(period).DayOfWeek) == 0 ? 7 : (int)startDay.AddMonths(period).DayOfWeek;
int shiftingDays = startDayOfWeek - newStartDayOfWeek;
if (shiftingDays > 3)
shiftingDays -= 7;
where startDay is the start date, and period is the number of months I want to shift to.
But this still fails some times, so any tips would be greately appreciated.
An example when this code fails would be:
startDate = 01.08.2016 (Monday) and period would be 5
After adding 5 months, I get 01.01.2017, which is Sunday, and the closest Monday would be on 02.01.2017, but I get -6 days.
Use this code. The idea is to divide the days by 7, round it, and multiply by 7.
DateTime endDate = startDay.AddMonths((int)period);
endDate = startDay.AddDays((int)Math.Round((double)(endDate - startDay ).Days / 7)*7);
Is that what you are looking for ?
static void Main( string[] args )
{
//DateTime startDay = DateTime.Now;
DateTime startDay = new DateTime( 2016, 8, 1 );
//DateTime startDay = new DateTime( 2016, 8, 10 );
DateTime newDay = startDay.AddMonths( 5 );
int startDayOfWeek = (int)startDay.DayOfWeek;
int newDayOfWeek = (int)newDay.DayOfWeek;
int shift1 = (7 + startDayOfWeek - newDayOfWeek) % 7;
int shift2 = (7 + newDayOfWeek - startDayOfWeek) % 7;
DateTime test = newDay + ((shift1 > shift2) ? - TimeSpan.FromDays( shift2 ) : TimeSpan.FromDays( shift1 ));
}
Can anyone please help me, how do I calculate fortnightly (14 days) logic using C#?, for a example 14 days start following sequence order on February
Monday start date 8 Feb (next 22 Feb, 7 March, 21 March etc..)
Thursday start date 11 February (next 25 Feb, 10 March, 24 March etc..)
Friday start date 12 February (next 26 Feb, 11 March, 25 March etc..)
My logic is not working for the 14 days day display, because 15 February will come 14 days add, it’ll display “First14days” date 29 February 2016, it is a wrong.
This is C# logic
Day.Days value are Monday, Thursday, Friday etc..
foreach (var Day in day)
{
Example Day.Days = Monday
Int 14days = (((int)Enum.Parse(typeof(DayOfWeek), Day.Days) - (int)today.DayOfWeek + 14) % 7);
DateTime First14days = today.AddDays(14days);
}
My output should be
Simply add TimeSpan.FromDays(14) to any date to get a fortnight further on
DateTime startDate = DateTime.Now;
TimeSpan fortnight = TimeSpan.FromDays(14);
for (int i = 0; i < 6; i++)
{
startDate += fortnight;
Console.WriteLine($"Date for fortnight {i}: {startDate:D}");
}
If I understand correct your question this code will be working for you.
DateTime time = DateTime.Now;
DateTime anotherTime = DateTime.Now;
var allTimes = new HashSet<DateTime>();
for (int i = 0; i < 6; i++)
{
anotherTime = time.AddDays(14);
time = anotherTime;
Console.WriteLine(anotherTime.ToLongDateString());
allTimes.Add(time);
}
// or with your example is possible to like this code.
foreach (var Day in day)
{
anotherTime = Day.AddDays(14);
time = anotherTime;
Console.WriteLine(anotherTime.ToLongDateString());
allTimes.Add(time);
}
First create two DataTime objects. then foreach few times, and in for loop statement set anotherTime = time.AddDays(14) after that set time = anotherTime.
//Output:
//Saturday, February 27, 2016
//Saturday, March 12, 2016
//Saturday, March 26, 2016
//Saturday, April 09, 2016
//Saturday, April 23, 2016
//Saturday, May 07, 2016
EDIT:
I create and HashSet where you can save all you DateTime who you make it.
So here's you all-in-one solution:
// determine the date of next given weekday
DateTime date = GetNextWeekday(DateTime.Today, DayOfWeek.Tuesday);
// create a list and add the start date (if you want)
List<DateTime> fortnights = new List<DateTime>() { date };
// add as many "fortnights" as you like (e.g. 5)
for (int i = 0; i < 5; i++)
{
date = date.Add(TimeSpan.FromDays(14));
fortnights.Add(date);
}
// use your list (here: just for printing the list in a console app)
foreach (DateTime d in fortnights)
{
Console.WriteLine(d.ToLongDateString());
}
Method to get the next weekday, from:
https://stackoverflow.com/a/6346190/2019384
public static DateTime GetNextWeekday(DateTime start, DayOfWeek day)
{
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysToAdd = ((int) day - (int) start.DayOfWeek + 7) % 7;
return start.AddDays(daysToAdd);
}
I have a code 2014P07W4 which means:
2014 = year
P07 = 7th month of the year
W4 = 4th week of the month.
I would like to work out the date of the First day of the 4th week in July 2014. In this example I would expect to see a date of 21/7/2014.
July 2014 weeks
Week 1 - 1st to 6th
Week 2 - 7th to 13th
Week 3 - 14th to 20th
Week 4 - 21st to 27th
Week 5 - 28th to 31st
From the code I know the week no = 4 then I want to be able to calculate the date 21/7/2014. I am assuming the first day of the week is a Monday
I am asking how to read that code and get the first day of the week specified
Hope this is clearer it has been a long day
You need to parse the code and extract the year, month, and weekNo an numbers.
Then, you can use this method to get the start day of the week:
int WeekStartDay(int year, int month, int weekNo)
{
DateTime monthStart = new DateTime(year, month, 1);
int monthStart_DayOfWeek = ((int)monthStart.DayOfWeek + 6) % 7;
int weekStart_DayOfMonth = 1;
if (1 < weekNo) {
weekStart_DayOfMonth += 7 - monthStart_DayOfWeek;
}
if (2 < weekNo) {
weekStart_DayOfMonth += 7 * (weekNo - 2);
}
return weekStart_DayOfMonth;
}
Take first day of month (2014/07/01), find next Monday (first day of 2nd week), add 14 days (first day of 4th week).
DateTime date = new DateTime(2014, 7, 1);
int daysToFirstDayOf2ndWeek = date.DayOfWeek == DayOfWeek.Monday
? 7
: ((int)DayOfWeek.Monday - (int)date.DayOfWeek + 7) % 7;
DateTime firstDayOf2ndWeek = date.AddDays(daysToFirstDayOf2ndWeek);
DateTime firstDayOf4thWeek = firstDayOf2ndWeek.AddDays(14);
may be this will works
string code = "2014P07W4";
int yr = int.Parse(code.Substring(0, 4));
int mnth = int.Parse(code.Substring(5, 2));
int week = int.Parse(code.Substring(8));
DateTime dt = new DateTime(yr, mnth, 1);
if (dt.DayOfWeek == DayOfWeek.Monday)
{
DateTime newdate = dt.AddDays((week - 1) * 7);
}
else
{
DateTime newdate = dt.AddDays((8 - (int)dt.DayOfWeek) % 7 + ((week - 2) * 7));
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to find the 3rd Friday in a month with C#?
Hi everyone,
I've wrote a little console utility that spits out a line into a text file. I want this line to include the second Friday of the current month. Is there any way to do this?
Thanks everyone!
Slight variation on #druttka: using an extension method.
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);
// CurDate = 2011.10.1 Occurance = 1, Day = Friday >> 2011.09.30 FIX.
if (fOc.Month < CurDate.Month) Occurrence = Occurrence+1;
return fOc.AddDays(7 * (Occurrence - 1));
}
Then called it like this:
for (int i = 1; i < 13; i++)
{
Console.WriteLine(new DateTime(2011, i,1).NthOf(2, DayOfWeek.Friday));
}
I would go for something like this.
public static DateTime SecondFriday(DateTime currentMonth)
{
var day = new DateTime(currentMonth.Year, currentMonth.Month, 1);
day = FindNext(DayOfWeek.Friday, day);
day = FindNext(DayOfWeek.Friday, day.AddDays(1));
return day;
}
private static DateTime FindNext(DayOfWeek dayOfWeek, DateTime after)
{
DateTime day = after;
while (day.DayOfWeek != dayOfWeek) day = day.AddDays(1);
return day;
}
Untested, but this should grab it.
DateTime today = DateTime.Today;
DateTime secondFriday =
Enumerable.Range(8, 7)
.Select(item => new DateTime(today.Year, today.Month, item))
.Where(date => date.DayOfWeek == DayOfWeek.Friday)
.Single();
fully tested:
for (int mo = 1; mo <= 12; mo++)
{
DateTime _date = new DateTime(yr, mo, 1);
DayOfWeek day = _date.DayOfWeek;
int d = 0;
if (day == DayOfWeek.Saturday)
d += 7;
var diff = DayOfWeek.Friday - day;
DateTime secFriday = _date.AddDays(diff + 7 + d);
Console.WriteLine(secFriday.ToString("MM\tddd\tdd"));
}
Final results:
Month Date
=====================
01 Fri 14
02 Fri 11
03 Fri 11
04 Fri 08
05 Fri 13
06 Fri 10
07 Fri 08
08 Fri 12
09 Fri 09
10 Fri 14
11 Fri 11
12 Fri 09