How to get "number" of day - c#

I would like to get the "number of the day. For example:
January the first would be 1.
Febuary the first would be the 32.
So that we get up a whole year with 365 days.
Sry for my bad english :)

DateTime.DayOfYear is what you want
DateTime.Now.DayOfYear
or whatever yourDate is;
yourDate.DayOfYear;

Use DayOfYear property of any DateTime object:
var date = new DateTime(2012, 1, 1);
var dayNumber = date.DayOfYear;

There's a DateTime property named: DayOfYear
Console.WriteLine(DateTime.Now.DayOfYear);
Or for any date:
var d = new DateTime(2012, 8, 30);
Console.WriteLine(d.DayOfYear);

like this
private int GetDaysInAYear(int year)
{
int days = 0;
for (int i = 1; i <= 12; i++)
{
days += DateTime.DaysInMonth(year, i);
}
return days;
}
and do this (method above to get the number of days in year)
DateTime.Now.DayOfYear

DateTime.Now.DayOfYear.ToString()

Related

Combine Monday to Sunday dates to textfile

This is a C# 4.0 WinForms app.
I'm trying to pull all the Monday dates in a given month (the fully spelled out Month name and day), and the days in all the Sundays. Then, using StreamWriter, write these to a text file.
I found the following code suggestion on enumerating through a month, on StackOverFlow below.
How to get every monday of given month?
public static IEnumerable<DateTime> AllDatesInMonth(int year, int month)
{
int days = DateTime.DaysInMonth(year, month);
for (int day = 1; day <= days; day++)
{
yield return new DateTime(year, month, day);
}
}
And then you can call with LINQ like so:
var mondays = AllDatesInMonth(2017, 7).Where(i => i.DayOfWeek == DayOfWeek.Monday);
I modified the suggestion to also pull the Sunday dates. I'm testing this, in order to make it part of a larger application.
This is what I've come up with so far, as shown below.
private void btnTestDayOWeek_Click(object sender, EventArgs e)
{
int curYear = DateTime.Now.Year;
int month = DateTime.Now.Month;
string outputFile = #"C:\dates2Compare.txt";
List<string> mondayList = new List<string>();
List<string> sundayList = new List<string>();
using (StreamWriter sw = new StreamWriter(outputFile))
{
var mondays = AllDatesInMonth(curYear, 3).Where(i => i.DayOfWeek == DayOfWeek.Monday);
var sundays = AllDatesInMonth(curYear, 3).Where(i => i.DayOfWeek == DayOfWeek.Sunday);
foreach (DateTime Monday in mondays)
{
mondayList.Add(Monday.ToString("MMMM d"));
}
foreach (DateTime Sunday in sundays)
{
sundayList.Add(Sunday.ToString("-d"));
}
var dayList = mondayList.Concat(sundayList);//attempt to join these 2-Lists
foreach (string dt in dayList)
{
sw.WriteLine(dt);
}
}
}
public static IEnumerable<DateTime> AllDatesInMonth(int year, int month)
{
int days = DateTime.DaysInMonth(year, month);
for (int day = 1; day <= days; day++)
{
yield return new DateTime(year, month, day);
}
}
I need to join the Monday to Sunday dates, like this, i.e.
March 1-7
March 8-14
But this is what I'm receiving so far.
March 1
March 8
March 15
March 22
March 29
-7
-14
-21
-28
Can someone suggest how to modify my code so that, the text file that is written to, correctly displays the Monday date with a "-" after it and then the Sunday date?
You are making it too complicated. Simply loop the days of the month in a split second:
int year = 2021;
int month = 3;
DateTime date = new DateTime(year, month, 1);
string monthName = date.ToString("MMMM");
int ultimo = date.AddMonths(1).AddDays(-1).Day;
for (int i = 0; i < ultimo - 6; i++)
{
DateTime monthDate = date.AddDays(i);
if (monthDate.DayOfWeek == DayOfWeek.Monday)
{
string line = string.Format(monthName + " {0}-{1}", monthDate.Day, monthDate.Day + 6);
Console.WriteLine(line);
// sw.WriteLine(line);
}
}
Output:
March 1-7
March 8-14
March 15-21
March 22-28
//var dayList = mondayList.Concat(sundayList);//attempt to join these 2-Lists
List<string> dayList = new List<string>();
int weekCount = Math.Min(mondayList.Count(), sundayList.Count());
for (int i = 0; i < weekCount; i++)
{
string concateValue = mondayList[i] + sundayList[i];
dayList.Add(concateValue);
}
When you Concat lists, the values stack on top of each other. You need to merge the lists together.

Get tasks done every Monday for the next 5 weeks

How do I get built-up start hours and end hours that if a user just wants to have done several tasks eg every Monday from 08 to 11 the next x number of weeks.
So how can I just do it in a smart way.
I have MoreAdd which tells how many weeks ahead it should make that way.
When I just create a single task. Then it looks like this.
var sTimer = model.StartTime;
var eTimer = model.EndTime;
SignUpInfo addSignUpInfo = new SignUpInfo
{
CompanyId = companyId,
Title = model.Title,
Info = model.Info,
StartTime = sTimer,
EndTimer = eTimer,
Closed = false,
Pay = PayValue,
TaskDone = false,
CreateTime = DateTime.Now,
CategoriId = model.SelectedKategori
};
_db.SignUpInfo.Add(addSignUpInfo);
_db.SaveChanges();
But how will I only do that if I write 5 then make it one from the next Monday and 5 times forward.
I guess you are struggling with determining the start- and end DateTimes for the next 5 weeks from the next Monday. You could use this method:
static IEnumerable<(DateTime start, DateTime end)> GetTimes(DateTime startTime, DateTime endTime, DayOfWeek startDay, int countWeeks)
{
if(endTime < startTime) throw new ArgumentException("TODO");
TimeSpan diff = endTime - startTime;
int daysUntilWeekDay = ((int) startDay - (int) startTime.DayOfWeek + 7) % 7;
DateTime beginningDate = startTime.AddDays(daysUntilWeekDay);
for (int i = 0; i <= countWeeks; i++)
{
DateTime date = beginningDate.AddDays(7 * i);
yield return (start: date, end:date.Add(diff));
}
}
Example:
DateTime dt = new DateTime(2019, 01, 20, 8, 0, 0); //yesterday, sunday, 8 o clock in the morning
foreach(var x in GetTimes(dt, dt.AddHours(3), DayOfWeek.Monday, 5))
Console.WriteLine("Start:{0} End:{1}", x.start, x.end);
With this method it's easy to build a loop that uses your existing code to save the tasks.

How do I find week numbers of a given date range in C#

I need to find the week numbers of a given date rage in C#.
Ex: date between 01/01/2014 and 14/01/2014
Week numbers are 1st,2nd and 3rd weeks, likewise.
Thanks.
Not the smartest way, but works!
var d1 = new DateTime(2014, 1, 1);
var d2 = new DateTime(2014, 1, 14);
var currentCulture = CultureInfo.CurrentCulture;
var weeks = new List<int>();
for (var dt = d1; dt < d2; dt =dt.AddDays(1))
{
var weekNo = currentCulture.Calendar.GetWeekOfYear(
dt,
currentCulture.DateTimeFormat.CalendarWeekRule,
currentCulture.DateTimeFormat.FirstDayOfWeek);
if(!weeks.Contains(weekNo))
weeks.Add(weekNo);
}
This should work:
public List<int> Weeks(DateTime start, DateTime end)
{
List<int> weeks=new List<int>();
var Week=(int)Math.Floor((double)start.DayOfYear/7.0); //starting week number
for (DateTime t = start; t < end; t = t.AddDays(7))
{
weeks.Add(Week);
Week++;
}
return weeks;
}
All this does is get the week of the start date, then loops through one week at a time until you get to the end date, incrementing the week and adding it to the list of weeks.
OK, let's start with a simple, unoptimized example. We'll simply examine every date between those dates and check what week of the year it is.
We can do that with a simple loop:
var end = new DateTime(2014, 1, 14);
for (var date = new DateTime(2014, 1, 1); date <= end; date = date.AddDays(1))
{
}
This will simply loop over every day between two dates. Now we need to examine those days to determine their day of week. To do this you need to consider a few things: What is the first day of a week? Sunday? Monday? Are we assuming gregorian calendar?
For our example, let's assume the first day of the week is a Sunday and we are indeed using the Gregorian calendar. Then we will check each date, and keep a list of unique weeks of the year using a HashSet:
var weekNumber = new HashSet<int>();
var end = new DateTime(2014, 1, 14);
var calendar = new GregorianCalendar();
for (var date = new DateTime(2014, 1, 1); date <= end; date = date.AddDays(1))
{
weekNumber.Add(calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DayOfWeek.Sunday));
}
The weekNumber Hashset now contains the weeks of the year.
Is this optimized? No. It checks far more dates than it needs to, but the implementation is simple and fast enough. Optimizing can be done as a separate task.
Easy. Here's the code that determines the week of the year for a single date. This should get you going:
int WeekOfYear(DateTime date, DayOfWeek dayOfWeekStart) {
//Find the first day of the year that's the start of week day. If it's not 1/1,
//then we have a first partial week.
bool firstPartialWeek = false;
DateTime firstFullWeekStart = new DateTime(date.Year, 1, 1);
while(firstFullWeekStart.DayOfWeekDay != dayOfWeekStart) {
firstFullWeekStart = firstOfWeek.AddDays(1);
firstPartialWeek = true;
}
//Return the week by integer dividing the date difference by seven,
//and adding in the potential first partial week
return (firstPartialWeek ? 1 : 0) + ((date - firstFullWeekStart).TotalDays / 7);
}

How to get date from day of year

How can I get date from day of year in C#?
I have this code :
int a = 53; // This is the day of year value, that I got previously
string b = Convert.ToDateTime(a).ToString(); // Trying to get the date
I need to get the value 22.2.2014. But this doesn't work, what should I do? Thanks in advance.
int dayOfYear = 53;
int year = DateTime.Now.Year; //Or any year you want
DateTime theDate = new DateTime(year, 1, 1).AddDays(dayOfYear - 1);
string b = theDate.ToString("d.M.yyyy"); // The date in requested format
Assuming you want the current year?
int a = 53;
DateTime date = new DateTime(DateTime.Now.Year, 1,1).AddDays(a -1);
int a = 53;
var dt = new DateTime(DateTime.Now.Year, 1, 1).AddDays(a - 1);
string b = dt.ToString();
Use
DateTime.AddDays()
Initialize a date to start of the year , then just add a to that using this function
http://msdn.microsoft.com/en-us/library/system.datetime.adddays(v=vs.110).aspx

Need help finding the second Wednesday of a year

I need help finding the second Wednesday of the year. Here is what I have done, but it doesn't seem to work.
DateTime baseDay = new DateTime(DateTime.Now.Year, 1, 5);
int secondWed = 5 + ((12 - (int)baseDay.DayOfWeek) % 7);
DateTime fullDate = new DateTime(DateTime.Now.Year, 1, secondWed);
Try this method instead:
DateTime dt = new DateTime(DateTime.Now.Year, 1, 8); //get second week of the year
while(dt.DayOfWeek != DayOfWeek.Wednesday) //loop until we find the next Wednesday
dt = dt.AddDays(1);
Based on the very good answer by Mark Ransom to How to find the 3rd Friday in a month with C#?. There is no looping here.
var year = 2011;
var firstDayOfMonth = new DateTime(year, 1, 1);
var daysUntilNextWednesday = DayOfWeek.Wednesday - firstDayOfMonth.DayOfWeek;
if (daysUntilNextWednesday < 0)
daysUntilNextWednesday += 7;
var firstWednesdayOfMonth = firstDayOfMonth.AddDays(daysUntilNextWednesday);
var secondWednesdayOfMonth = firstWednesdayOfMonth.AddDays(7);
You can merge the last two lines into one for slightly better performance.
May be this helps
DateTime startDate = new DateTime(DateTime.Now.Year, 1, 1);
int c = (int)startDate.DayOfWeek;
int n = (int)DayOfWeek.Wednesday;
int weekcount=2;
int diff = (7 - c + n);
int days= (diff > 7) ? diff % 7 : diff;
startDate.AddDays((weekcount-1)*7+ days );
Something this simple would also work...
int weekNumber = 2;
DateTime seekingDate = new DateTime(DateTime.Now.Year, 1, 1);
while (seekingDate.DayOfWeek != DayOfWeek.Wednesday)
seekingDate = seekingDate.AddDays(1);
seekingDate.AddDays(7 * (weekNumber - 1));
Of course, I would use variable for the weekday and the week number.
I believe this would also work:
var date = new DateTime(DateTime.Now.Year,1,1);
if(date.DayOfWeek > DayOfWeek.Tuesday)
date = date.AddDays(9 - (int)date.DayOfWeek);
else if(date.DayOfWeek < DayOfWeek.Tuesday)
date = date.AddDays(2 - (int)date.DayOfWeek);
date = date.AddDays(7);

Categories

Resources