I'm learning C# and I wanted to make a calendar to learn DateTime. I did make a calendar but now I want to see previous months days in first week like in this photo. I tried few things but I really don't remember all.
Here is my code and if there any way to improve it just say.
I'm using WinForms for ui.
DateTime now = DateTime.Now;
Month = now.Month;
Year = now.Year;
// count of days of the month
int days = DateTime.DaysInMonth(Year, Month);
// first day of the month
DateTime startofthemonth = new DateTime(Year, Month,1);
// last day of the month
var endofthemonth = startofthemonth.AddDays(-1);
// convert the startofthemonth to int
int dayoftheweek = Convert.ToInt32(startofthemonth.DayOfWeek.ToString("d")) + 6;
// convert the endofthemonth to int
int lastdayinmonth = Convert.ToInt32(endofthemonth.DayOfWeek.ToString("d"));
// blank user control
for (int i = lastdayinmonth; i <= lastdayinmonth; i--)
{
UCBlankDay uCBlankDay = new UCBlankDay();
uCBlankDay.BlankDays(i);
flowLayoutPanel1.Controls.Add(uCBlankDay);
}
// day user control
for (int i = 1; i <= days; i++)
{
UCDay uCDay = new UCDay();
uCDay.Days(i);
flowLayoutPanel1.Controls.Add(uCDay);
}
}
to be clear code works without showing previous months days in first week
I've recently done a calendar and I found that when you are in the month view, it's better to divide your month in weeks first instead of days right away.
I would use your 1st day of the month and find the first day of the week doing something like this:
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
return dt.AddDays(-1 * diff).Date;
}
startofthemonth = date.StartOfMonth().StartOfWeek(startDay);
I would then iterate by weeks instead of days like this
do
{
Weeks.Add(new UCBlankWeek(**Your day logic will be inside this constructor**));
startofthemonth = startofthemonth.AddDays(7);
currentMonth = startofthemonth.Month;
}
while (currentMonth == MonthNumber);
You can loop 7 times inside the constructor of everyweek and put you logic in there.
Hope this helps with your issue!
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.
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
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.
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 ;-)
I am trying to list the next 10 weeks
The result should be like this:
Week Year
----------------
45: 2012
46: 2012
47: 2012
48: 2012
49: 2012
50: 2012
51: 2012
52: 2012
1: 2013
2: 2013
some years there is a week 53, and this year the 31st of December is on a Monday, is this week 1 or week 53??
Anyways, I want to skip week 53, whenever it occours. This means that 1 or 2 days will not be a part of any week on the list, but this doesn't matter.
some years there is a week 53, and this year the 31st of December is on a Monday, is this week 1 or week 53??
Assuming you mean "week of week-year", that would be week 1 of week-year 2013.
In the ISO calendar, the first week of a week-year is the first Monday-Sunday week which has 4 days or more in it.
It's not clear why you'd want to skip week 53 - it doesn't just skip 1 or 2 days, it skips a whole week.
Of course, this really is assuming you mean the ISO definition of "week of year". If you don't, it's a different matter. You need to clarify your requirements before you do anything else.
To obtain the week-of-week-year from .NET, you can use Calendar.GetWeekOfYear - for the ISO definition you'd use CalendarWeekRule.FirstFourDayWeek and DayOfWeek.Monday. I don't know whether there's anything to get the week-year itself though.
As a blatant plug, in my Noda Time there's support for both WeekYear and WeekOfWeekYear on dates, and you can construct a date for a given week-year/week-of-week-year/day-of-week combination.
i just wrote a small console app that does just that:
static void Main(string[] args)
{
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
DateTime dt = DateTime.Now; //Use current date as starting point
for (int i = 0; i < 10; i++)
{
int weekNo = ci.Calendar.GetWeekOfYear(
dt,
ci.DateTimeFormat.CalendarWeekRule,
ci.DateTimeFormat.FirstDayOfWeek
);
int year = ci.Calendar.GetYear(dt);
if (weekNo == 53) //if week number==53, then go to next week
{
dt = dt.AddDays(7);
weekNo = ci.Calendar.GetWeekOfYear(
dt,
ci.DateTimeFormat.CalendarWeekRule,
ci.DateTimeFormat.FirstDayOfWeek
);
year = ci.Calendar.GetYear(dt);
}
dt = dt.AddDays(7);
Console.WriteLine(weekNo + "-" + year);
}
}
output today:
46-2012
47-2012
48-2012
49-2012
50-2012
51-2012
52-2012
1-2013
2-2013
3-2013
from msdn http://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear.aspx
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
DateTime date1 = new DateTime(2011, 1, 1);
Calendar cal = dfi.Calendar;
Console.WriteLine("{0:d}: Week {1} ({2})", date1,
cal.GetWeekOfYear(date1, dfi.CalendarWeekRule,
dfi.FirstDayOfWeek),
cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));
}
}
// The example displays the following output: // 1/1/2011: Week 1 (GregorianCalendar)
The following will work based off of the number of weeks since the start of the year.
if you want this to be based off of full weeks then you'll need to determine an offset of 0 or 1 at the start based on the day of the first week of the year.
public class Week
{
public Week(int weekOfYear, int year)
{
WeekOfYear = weekOfYear;
Year = year;
}
public int WeekOfYear { get; private set; }
public int Year { get; private set; }
}
public IEnumerable<Week> Next10Weeks(DateTime startDate)
{
DateTime tempDate = startDate;
for (int i = 0; i < 10; i++)
{
//add one to first parameter if you want the 1-indexed week instead of 0 indexed
yield return new Week(tempDate.DayOfYear % 7, tempDate.Year);
tempDate.AddDays(7);
}
}