calculate difference between 2 dates from datetimepicker [duplicate] - c#

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

Related

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

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);
}

await x.ShowAsync(); shown in Windows Phone 8.1 app Error

An exception is thrown when using "await" operator inside a function as follows:
The 'await' operator can only be used within an async method.
Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
int snooze;
string audioSrc;
int year = datepicker.Date.Year;
int month = datepicker.Date.Month;
int day = datepicker.Date.Day;
int hour = timepicker.Time.Hours;
int min = timepicker.Time.Minutes;
int sec = timepicker.Time.Seconds;
// string audioSrc = alrm_sound.SelectionBoxItem.ToString();
try
{
snooze = Convert.ToInt16(CustomSnoozeTime.SelectionBoxItem.ToString());
}
catch
{
snooze = 5;
}
try
{
audioSrc = alrm_sound.SelectionBoxItem.ToString();
}
catch
{
audioSrc = "Default";
}
DateTime myDate1 = new DateTime(year, month, day, hour, min, sec);
DateTime myDate2 = DateTime.Now;
TimeSpan myDateResult = new TimeSpan();
myDateResult = myDate1 - myDate2;
if (myDate2 > myDate1)
{
var x = new MessageDialog("Invalid date or time");
await x.ShowAsync();
}
else
{
string title = "Alarm!";
string message = alm_msg.Text;
string imgURL = "ms-appx:///Assets/Capture.PNG";
string toastXmlString =
"<toast><visual version='1'><binding template='toastImageAndText02'><text id='1'>"
+ title + "</text><text id='2'>"
+ message + "</text><image id='1' src='" + imgURL + "'/></binding></visual>\n" +
"<commands scenario=\"alarm\">\n" +
"<command id=\"snooze\"/>\n" +
"<command id=\"dismiss\"/>\n" +
"</commands>\n" +
"<audio src='ms-winsoundevent:Notification." + audioSrc + "'/>" +
"</toast>";
Windows.Data.Xml.Dom.XmlDocument toastDOM = new Windows.Data.Xml.Dom.XmlDocument();
toastDOM.LoadXml(toastXmlString);
var toastNotifier1 = Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier();
double x1 = myDateResult.TotalSeconds;
int customSnoozeSeconds = snooze * 60;
TimeSpan snoozeInterval = TimeSpan.FromSeconds(customSnoozeSeconds);
var customAlarmScheduledToast = new Windows.UI.Notifications.ScheduledToastNotification(toastDOM, DateTime.Now.AddSeconds(x1), snoozeInterval, 0);
toastNotifier1.AddToSchedule(customAlarmScheduledToast);
var x = new MessageDialog("Alarm Set!");
await x.ShowAsync();
}
}
catch
{ }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
int snooze;
string audioSrc;
int year = datepicker.Date.Year;
int month = datepicker.Date.Month;
int day = datepicker.Date.Day;
int hour = timepicker.Time.Hours;
int min = timepicker.Time.Minutes;
int sec = timepicker.Time.Seconds;
// string audioSrc = alrm_sound.SelectionBoxItem.ToString();
try
{
snooze = Convert.ToInt16(CustomSnoozeTime.SelectionBoxItem.ToString());
}
catch
{
snooze = 5;
}
try
{
audioSrc = alrm_sound.SelectionBoxItem.ToString();
}
catch
{
audioSrc = "Default";
}
DateTime myDate1 = new DateTime(year, month, day, hour, min, sec);
DateTime myDate2 = DateTime.Now;
TimeSpan myDateResult = new TimeSpan();
myDateResult = myDate1 - myDate2;
if (myDate2 > myDate1)
{
var x = new MessageDialog("Invalid date or time");
await x.ShowAsync();
}
else
{
string title = "Alarm!";
string message = alm_msg.Text;
string imgURL = "ms-appx:///Assets/Capture.PNG";
string toastXmlString =
"<toast><visual version='1'><binding template='toastImageAndText02'><text id='1'>"
+ title + "</text><text id='2'>"
+ message + "</text><image id='1' src='" + imgURL + "'/></binding></visual>\n" +
"<commands scenario=\"alarm\">\n" +
"<command id=\"snooze\"/>\n" +
"<command id=\"dismiss\"/>\n" +
"</commands>\n" +
"<audio src='ms-winsoundevent:Notification." + audioSrc + "'/>" +
"</toast>";
Windows.Data.Xml.Dom.XmlDocument toastDOM = new Windows.Data.Xml.Dom.XmlDocument();
toastDOM.LoadXml(toastXmlString);
var toastNotifier1 = Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier();
double x1 = myDateResult.TotalSeconds;
int customSnoozeSeconds = snooze * 60;
TimeSpan snoozeInterval = TimeSpan.FromSeconds(customSnoozeSeconds);
var customAlarmScheduledToast = new Windows.UI.Notifications.ScheduledToastNotification(toastDOM, DateTime.Now.AddSeconds(x1), snoozeInterval, 0);
toastNotifier1.AddToSchedule(customAlarmScheduledToast);
var x = new MessageDialog("Alarm Set!");
await x.ShowAsync();
}
}
catch
{ }
}
Add the "async" keyword in the method's declaration.
for example, if your method is like -
public void MyMethod()
{
await x.ShowAsync();
}
change it like this -
public async void MyMethod()
{
await x.ShowAsync();
}
Update :-
Also, if your method returns a value/object, do it like this -
public async Task<int> MyMethod()
{
int i = await x.ShowAsync();
return i;
}
Update:-
Change your function as follows-
private void Button_Click(object sender, RoutedEventArgs e)
Change this to-
private async void Button_Click(object sender, RoutedEventArgs e)
You need to add the async modifier to the Button_Click method like so:
private async void Button_Click(object sender, RoutedEventArgs e)
{
// rest of code
}

Invalid cast from double to datetime error

Hi I am getting invalid cast from double to datetime error when i run my ASP.NET MVC code.
This is my code :
Update: Hi I am adding my full code below. Please have a look into that.
Boolean locked = false;
if (frmcollection["lockStart"] != null && frmcollection["lockStart"] != "")
{
locked = Convert.ToBoolean(frmcollection["lockStart"].ToString());
}
else if (datelock == "")
{
locked = Convert.ToBoolean("0");
}
Boolean valid = true;
double inteval = 86400000 * Convert.ToDouble(frmcollection["autoFrequency"].ToString());
DateTime schedulestartDate = Convert.ToDateTime(frmcollection["autoStart"].ToString());
int startHour = Convert.ToInt32(frmcollection["autoStartHour"].ToString());
DateTime sd = schedulestartDate;
sd.AddHours(startHour);
DateTime filterStart = Convert.ToDateTime(frmcollection["periodStart"].ToString());
int filterStartHour = Convert.ToInt32(frmcollection["periodStartHour"].ToString());
DateTime fsd = filterStart;
fsd.AddHours(filterStartHour);
DateTime filterEnd = Convert.ToDateTime(frmcollection["periodEnd"].ToString());
int filterEndHour = Convert.ToInt32(frmcollection["periodEndHour"].ToString());
DateTime fed = filterEnd;
fed.AddHours(filterEndHour);
double sDate = sd.Second;
double sPeriod = sDate - fsd.Second;
double ePeriod = sDate - fed.Second;
if (sPeriod < ePeriod || sPeriod < 0 || ePeriod < 0)
{
valid = false;
}
if (valid)
{
for (int i = 0; i < 5; i++)
{
DateTime date = Convert.ToDateTime(sDate + (inteval * i));
if (locked)
{
DateTime psdate = Convert.ToDateTime(sDate - sPeriod);
}
else
{
DateTime psdate = Convert.ToDateTime(sDate + (inteval * i) - sPeriod);
}
DateTime pedate = Convert.ToDateTime(sDate + (inteval * i) - ePeriod);
}
}
else
{
}
When i debug I am gettin error in this line :
DateTime date = Convert.ToDateTime(sDate + (inteval * i));
Can someone help me in this??
You're adding a double to whatever interval * i resolves to.
You can't convert (cast) that to a DateTime, which is exactly what the error is telling you.
It seems as if you're looking for the date some (interval * i) seconds after the date "sd". If so, try:
for (int i = 0; i < 5; i++)
{
DateTime date = sd.AddSeconds(inteval * i);
if (locked)
{
DateTime psdate = sd.AddSeconds(-sPeriod);
}
else
{
DateTime psdate = sd.AddSeconds((inteval * i) - sPeriod));
}
DateTime pedate = sd.AddSeconds((inteval * i) - ePeriod);
}
//...
DateTime has a lot of methods to perform calculations on a specific date. For example DateTime.AddMillisecons which takes a double and returns a date.
MSDN DateTime.AddMilliseconds

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!

Format the TimeSpan string

I have a small C# program that has a calendar and 7 labels. When I select a date the labels display the days and dates of that week.
The labels are populated using the TimeSpan string what I want to do is format this string so that it only displays the days and dates with out the times.
This is the code I have so far:
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
DateTime dTime = new DateTime();
dTime = monthCalendar1.SelectionStart;
dTime -= new TimeSpan((int)dTime.DayOfWeek, 0, 0, 0 );
for (int i = 1; i < 8; i++)
{
var dt = dTime.AddDays(i);
lb[i].Text = dt.DayOfWeek + " : " + dt.Date;
}
}
You can call dt.Date.ToShortDateString().
You have multiple options.
You can use ToShortDateString() method for the DateTime type
lb[i].Text = dt.DayOfWeek + " : " + dt.Date.ToShortDateString()
or you can provide of a format to the ToString("format") method to specify exactly what you want it to look like.
lb[i].Text = dt.DayOfWeek + " : " + dt.Date.ToString("MM/dd/yyyy");
Try with DateTime.ToShortDateString() method;
Converts the value of the current DateTime object to its equivalent
short date string representation.
DateTime dt = DateTime.Now;
label8.Text = dt.Date.ToShortDateString());
You can learn more details from Custom Date and Time Format Strings

Categories