How do I output the date of all Mondays this year? - c#

I'm trying to output the dates of all Mondays this year, but my if element won't work with the conditions I'm giving it.
This is my code:
static void Main(string[] args)
{
var dagEtt = new DateTime(DateTime.Now.Year, 1, 1);
while (dagEtt <= DateTime.MaxValue)
{
if (dagEtt == DayOfWeek.Monday)
Console.WriteLine(dagEtt);
dagEtt = dagEtt.AddDays(1);
}
}

I changed your code a little bit
var start = new DateTime(DateTime.UtcNow.Year, 1, 1);
var end = start.AddYears(1);
while (start < end)
{
if (start.DayOfWeek == DayOfWeek.Monday)
{
Console.WriteLine(start);
start = start.AddDays(7);
}
else
start = start.AddDays(1);
}

You can calculate the first Monday of the year using the % operator. This greatly simplifies your loop.
static void Main(string[] args)
{
int year = DateTime.Now.Year;
DateTime startDate = FirstMonday(year);
while (startDate.Year == year)
{
Console.WriteLine(startDate);
startDate = startDate.AddDays(7);
}
}
https://stackoverflow.com/a/5665161/3194005
public static DateTime FirstMonday(int year)
{
var firstDay = new DateTime(year, 1, 1);
return new DateTime(year, 1, (8 - (int)firstDay.DayOfWeek) % 7 + 1);
}

Related

C# Windows Application Timer Stops

I have an Windows Application which uses timer like in the screen:
timer it's used to run a method every X minutes between 08:00:00 (Start Time) and 21:00:00 (Stop Time)
In the screen:
Next download Start at: shows what time the next run will occur
Time Left: shows the remaining time until next run will occur
Download Interval: time span between two runs
The method runs when the Next download Start = Current Time.
My issue is that event that the application is open and runs, the timer just stops after a while.
Any ideas why this happens, is this normal or am I doing something wrong in my code (i can post it if needed but now I was just asking to see if it's normal)?
Is there a way to prevent it or shell I create a checker and check his status regularly?
Thanks in advance for your support!
private System.Windows.Forms.Timer timerFrequency = new System.Windows.Forms.Timer();
public void LoadGeneraInfoPanel()
{
timerFrequency.Interval = 1000;
timerFrequency.Enabled = true;
this.timerFrequency.Tick += new System.EventHandler(this.timerFrequency_Tick);
timerFrequency.Start();
}
private void timerFrequency_Tick(object sender, EventArgs e)
{
txtGICurrTime.Text = DateTime.Now.ToString("HH:mm:ss");
if (drSystemParam["Auto"].ToString() == "True" && timerFrequency.Enabled)
{
if (txtGIFrequency.Text.ToString() != string.Empty && txtGIStopTime.Text.ToString() != string.Empty && txtGIStartTime.Text.ToString() != string.Empty)
{
int iHours = Convert.ToInt32(txtGIFrequency.Text.Substring(0, 2));
int iMinutes = Convert.ToInt32(txtGIFrequency.Text.Substring(3, 2));
int iSeconds = Convert.ToInt32(txtGIFrequency.Text.Substring(6, 2));
DateTime dCurrStartTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, Convert.ToInt32(txtGIStartTime.Text.Substring(0, 2)), Convert.ToInt32(txtGIStartTime.Text.Substring(3, 2)), Convert.ToInt32(txtGIStartTime.Text.Substring(6, 2)));
DateTime dCurrStopTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, Convert.ToInt32(txtGIStopTime.Text.Substring(0, 2)), Convert.ToInt32(txtGIStopTime.Text.Substring(3, 2)), Convert.ToInt32(txtGIStopTime.Text.Substring(6, 2)));
DateTime dCurrStartDownloadTime = dCurrStartTime;
for (int j = 0; dCurrStartDownloadTime < DateTime.Now & dCurrStartDownloadTime <= dCurrStopTime; j++)
dCurrStartDownloadTime = dCurrStartDownloadTime.AddHours(iHours).AddMinutes(iMinutes).AddSeconds(iSeconds);
var result = dCurrStartDownloadTime;
if (DateTime.Now > dCurrStartTime && DateTime.Now < dCurrStopTime.AddHours(-iHours).AddMinutes(-iMinutes).AddSeconds(-iSeconds))
{
if (txtNextDownloadTime.Text == String.Empty)
txtNextDownloadTime.Text = result.ToString("HH:mm:ss");
TimeSpan diff = result - DateTime.Now.AddSeconds(-1);
txtGITimeLeft.Text = string.Format("{0}:{1}:{2}", diff.Hours.ToString().PadLeft(2, '0'), diff.Minutes.ToString().PadLeft(2, '0'), diff.Seconds.ToString().PadLeft(2, '0'));
if (DateTime.Now.ToString("HH:mm:ss") == txtNextDownloadTime.Text)
{
timerFrequency.Stop();
txtNextDownloadTime.Text = result.ToString("HH:mm:ss");
Thread.Sleep(800);
timerFrequency.Enabled = true;
timerFrequency.Start();
btnEecuteMethod_Click(sender, e);
}
}
else
{
result = dCurrStartTime.AddDays(1);
txtNextDownloadTime.Text = result.ToString("HH:mm:ss");
TimeSpan diff = result - DateTime.Now.AddSeconds(-1);
txtGITimeLeft.Text = string.Format("{0}:{1}:{2}", diff.Hours.ToString().PadLeft(2, '0'), diff.Minutes.ToString().PadLeft(2, '0'), diff.Seconds.ToString().PadLeft(2, '0'));
}
}
else
{
timerFrequency.Enabled = false;
timerFrequency.Stop();
}
}
}

How to parse by one line?

I am looking for a solution about how to get all of my int Parses within one line. At the moment when I start my program I have to enter day, month and year. It is all done line by line. I want a solution or method where this does all of my parsing within one line and within a format of "dd/MM/yyyy".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace date
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("please enter date as dd/MM/yyyy");
int day;
int month;
int year;
day = int.Parse(Console.ReadLine());
month = int.Parse(Console.ReadLine());
year = int.Parse(Console.ReadLine());
Date i = new Date(day, month, year);
Console.WriteLine("{0}/{1}/{2}", i.day, i.month, i.year);
Console.ReadLine();
}
class Date
{
public int month; // 1-12
public int day; // 1-31 depending on month
int value = 1;
public int year
{
get;
private set;
}
public Date(int day, int month, int year)
{
this.day = day;
this.month = month;
this.year = year;
}
public int GetYear()
{
return year;
}
public void SetYear()
{
if (value > 1900 && value <= 2020)
year = value;
else
throw new ArgumentOutOfRangeException("year", value, "out of bounds");
}
private int Month
{
get { return month; }
set
{
if (value > 0 && value <= 12)
month = value;
else
throw new ArgumentOutOfRangeException("Month", value, "Month must be 1-12");
}
}
public int GetDay()
{
return day;
}
public void SetDay()
{
int[] days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (value > 0 && value <= days[month])
day = value;
else if (month == 2 && value == 29 &&
year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
day = value;
else
throw new ArgumentOutOfRangeException("days", value, "day is out of range");
}
}
}
}
You can use DateTime.Parse/TryParse or DateTime.ParseExact/TryParseExact:
string line = Console.ReadLine();
DateTime dt;
bool validDate = DateTime.TryParseExact(line,"dd/MM/yyyy", DateTimeFormatInfo.InvariantInfo,DateTimeStyles.None, out dt);
if(validDate)
Console.WriteLine(dt.ToLongDateString()); // now correctly initialized
With this format also DateTime.Parse/DateTime.TryParse works:
validDate = DateTime.TryParse(line, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt);
I use DateTimeFormatInfo.InvariantInfo to prevent that your local date separator is used instead of /(in case it's different).
Once it is parsed to DateTime it's trivial to create your Date instance:
Date d = new Date(dt.Day, dt.Month, dt.Year);
If you do NOT want to use DateTime.(Try)Parse, you can add a parse method with a Regex in your Date class:
public static Date ParseFromString(string s)
{
//string s = "24/12/2015";
Regex r = new Regex(#"(\d+)[\/](\d+)[\/](\d+)");
Match m = r.Match(s);
if (m.Success)
{
return new Date(m.Groups[1], m.Groups[2], m.Groups[3]);
}
else
{
// throw exception
}
}
You can't parse dd/MM/yyyy formatted string to int because it is not a valid string.
You need to parse it to DateTime first and you can use it's properties to get it's day, month and year as a numbers.
For example;
Console.WriteLine("please enter date as dd/MM/yyyy");
DateTime dt = DateTime.ParseExact(Console.ReadLine(), "dd/MM/yyyy",
CultureInfo.InvariantCulture);
int day = dt.Day;
int month = dt.Month;
int year = dt.Year;
Or you can use TryParseExact if you don't wanna throw exception if input is not dd/MM/yyyy format.
I am not wanting to use the preset DateTime class but I am using my
own "Date" class
If so, after you parse it, you can create your Date class instance with Date(int day, int month, int year) constructor based on this dt value as;
Date myDt = new Date(dt.Day, dt.Month, dt.Year);

How to determine if given date falls in next week/month

for example I have to choose in datetimepicker May 16,2014 the messge box will pop out "This Week" and if I choose in datetimepicker May 20,2014 it will pop out "Next Week" and also June 20,2014 will pop out "Next Month".
I tried this..
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek firstDayOfWeek = ci.DateTimeFormat.FirstDayOfWeek;
int offset = firstDayOfWeek - DateTime.Now.DayOfWeek;
DayOfWeek lastDayOfWeek = DateTime.Now.AddDays(offset).AddDays(6).DayOfWeek;
DateTime nextmonth = DateTime.Now.AddMonths(1);
DateTime input = DateTime.Now.AddDays(1);
input = dateTimePicker1.Value;
DateTime startOfWeek = DateTime.Today;
while (startOfWeek.DayOfWeek != firstDayOfWeek)
startOfWeek = startOfWeek.AddDays(-1);
DateTime endOfWeek = DateTime.Now;
while (endOfWeek.DayOfWeek != lastDayOfWeek)
endOfWeek = endOfWeek.AddDays(1);
bool thisWeek = input >= startOfWeek && input <= endOfWeek;
bool Thismonth = input == startOfWeek && input < endOfWeek;
bool nextMonth = input == nextmonth;
if (thisWeek == true)
{
label1.Text = "This Week";
}
else if (thisWeek == false)
{
label1.Text = "Next Week";
}
else if (nextMonth == true)
{
label1.Text = "Next Month";
}
Not too much of a problem to do. C# provides lots of Date Time Functions, but not "Is this week" although you could write an extension method for this.
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek firstDayOfWeek = ci.DateTimeFormat.FirstDayOfWeek;
int offset = firstDayOfWeek - DateTime.Now.DayOfWeek;
DayOfWeek lastDayOfWeek = DateTime.Now.AddDays(offset).AddDays(6).DayOfWeek;
DateTime input = DateTime.Now.AddDays(1);
DateTime startOfWeek = DateTime.Today;
while (startOfWeek.DayOfWeek != firstDayOfWeek)
startOfWeek = startOfWeek.AddDays(-1);
DateTime endOfWeek = DateTime.Now;
while (endOfWeek.DayOfWeek != lastDayOfWeek)
endOfWeek = endOfWeek.AddDays(1);
Console.WriteLine("Week starts: " + startOfWeek);
Console.WriteLine("Week ends: " + endOfWeek);
Console.WriteLine("Input was: " + input);
Console.Write("Is input this week? ");
bool thisWeek = input >= startOfWeek && input <= endOfWeek;
Console.WriteLine(thisWeek);

calculate difference between 2 dates from datetimepicker [duplicate]

This question already has answers here:
date difference using datepicker in wpf
(2 answers)
Closed 8 years ago.
I want to calculate the differences between two dates, one picked form dateTimePicker1 and the other one 20 February of 2014 and store it in a string to added to my array and be able to display it in another form
THIS is my code:
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
int differenceInDays = ts.Days;
string differenceAsString = differenceInDays.ToString();
return ts;
}
public class Patient
{
public string patientidString;
public string firstNameString;
public string lastNameString;
public string dateString;
public string differenceAsString;
public Patient()
{
patientidString = "";
firstNameString = "";
lastNameString = "";
dateString = "";
}
}
//Array
Patient[] patientInfo = new Patient[10];
private void button1_Click(object sender, EventArgs e)
{
TimeSpan difference = getDateDifference(new DateTime(2014, 2, 20), dateTimePicker1.Value);
if (textBox1.Text.Length == 0 || textBox2.Text.Length == 0 || textBox3.Text.Length == 0)
{
MessageBox.Show(" Patient id, first name and last name cannot be empty");
}
else
try
{
foreach (Patient patientinfoIndex in patientInfo)
patientInfo[itemCountInteger].patientidString = textBox1.Text;
patientInfo[itemCountInteger].firstNameString = textBox2.Text;
patientInfo[itemCountInteger].lastNameString = textBox3.Text;
patientInfo[itemCountInteger].dateString = dateTimePicker1.Text;
string names = patientInfo[itemCountInteger].patientidString + " " + patientInfo[itemCountInteger].firstNameString + " " + patientInfo[itemCountInteger].lastNameString;
listBox1.Items.Add(names);
itemCountInteger++;
listBox1.SelectedItem = names;
}
catch
{
MessageBox.Show("Contacts are limited to 20. Please delete some contacts prior to adding more.");
}
}
//Search Button search a patients name and display his surname in the label if patient is found display his surname
private void button2_Click(object sender, EventArgs e)
{
int intTest = 0;
for (int x = 0; x < patientInfo.Length; x++)
{
if (textBox4.Text == patientInfo[x].patientidString)
{
label6.Text = (patientInfo[x].firstNameString + " " + patientInfo[x].lastNameString);
PatientForm patientform = new PatientForm();
patientform.Show();
patientform.label6.Text = (patientInfo[x].patientidString);
patientform.label7.Text = (patientInfo[x].firstNameString);
patientform.label8.Text =(patientInfo[x].lastNameString);
patientform.dateTimePicker1.Text = (patientInfo[x].dateString);
patientform.label9.Text = (patientInfo[x].differenceAsString);
intTest = 1;
break;
}
}
if (intTest == 0)
{
label6.Text = ("not found");
}
}
DateTime febDate = new DateTime(2014, 2, 20);
DateTime pickerDate = myDateTimePicker.Value;
TimeSpan tspan = febDate - pickerDate;
int differenceInDays = tspan.Days;
string differenceAsString = differenceInDays.ToString();
If differenceInDays < 0 then multiply it by -1.
Note: In this case it's very easy to get the difference in hours, minutes or seconds as well.
Here's an example of the above code in it's own method:
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
return ts;
}
And when you want to trigger this method:
TimeSpan difference = getDateDifference(new DateTime(2014, 2, 20), dateTimePicker.Value);
//Now you can do what you want with the TimeSpan.
int differenceInDays = difference.Days;
int differenceInHours = difference.Hours;
Console.WriteLine(differenceInDays.ToString());
DateTime a = new DateTime.Parse(string);
Console.WriteLine(datePicker.Value.Subtract(a).TotalMinutes);
You can subtract any two dates and it will work.
DateTime date1 = new DateTime(2014,02,20);
DateTime date2 = dateTimePicker1.Value as DateTime;
TimeSpan difference = date1 - date2; //dunno what difference you need so you can swap these

Calculate DateTime for upcoming day of week

This is the code I have at the moment:
String getDayRequested;
public void setDay(String getDayFromForm1)
{
getDayRequested = getDayFromForm1;
{
if (getDayRequested.Contains("today"))
{
getDayRequested = DateTime.Today.DayOfWeek.ToString();
}
else if (getDayRequested.Contains("tomorrow"))
{
getDayRequested = DateTime.Today.AddDays(1).DayOfWeek.ToString();
}
}
This checks my TextBox.Text string from Form1, and checks to see if the text "today" or "tomorrow" is in it.
Can anyone help me in the right direction of how to check the string for information asked about upcoming days; ie: "What will be the date this saturday", and add the appropriate number of days depending on what the day is when asked.
UPDATE
Using the code in the accepted answer, I used the following in my above else if statement to complete what I was after:
else if (getDayRequested.Contains("monday"))
{
getDayRequested = GetFutureDay(DateTime.Now, DayOfWeek.Monday).ToString("dd");
}
This handy little method will return a future day of the week.
public DateTime GetFutureDay(DateTime start, DayOfWeek day)
{
int daysToAdd = (day - start.DayOfWeek + 7) % 7;
return start.AddDays(daysToAdd);
}
It would be called like:
var day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), getDayFromForm1);
var getDayRequested = GetFutureDay(DateTime.Now, day);
Consider the following snippet of code...
DateTime date;
public void setDay(String day)
{
DayOfWeek futureDay = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), day);
int futureDayValue = (int)futureDay;
int currentDayValue = (int)DateTime.Now.DayOfWeek;
int dayDiff = futureDayValue - currentDayValue;
if (dayDiff > 0)
{
date = DateTime.Now.AddDays(dayDiff);
}
else
{
date = DateTime.Now.AddDays(dayDiff + 7);
}
}
Good Luck!

Categories