how to compare date and time - c#

I am developing an application called reminder using C# - visual studio 2010 . My Application reminds every event entered. Solution bellow works properly but I need to express this just using "datetimepicker" (calendar for date selection is not used)
MyRemindTime =dlg.MymonthCalendar.SelectionStart.AddHours(dlg.MyTimePicker.Value.Hour).AddMinutes(dlg.MyTimePicker.Value.Minute).AddSeconds(dlg.MyTimePicker.Value.Second);
timer1.Enabled = true;
private void timer1_Tick(object sender, EventArgs e)
{
if (MyRemindTime.CompareTo (DateTime.Now)<0)
{
timer1.Enabled = false;
MessageBox.Show("Alarm");
}
}
Could you please help me how to properly express MyRemindTime? I need to compare current date and time with datetimepicker. Time and datum has to be compared.

You can get the selected date/time as :
DateTime reminderTime = myDateTimePicker.Value;
And compare with the current time:
if(reminderTime < Datetime.Now)
//reminder time has passed

Related

Proper way for datepickers validaton in c#? (windows forms)

Just can't get it with datepicker validation.
I have datepicker From and datepicker To, so I want to prevent the user from doing some kung fu and seting datepicker From to be bigger than datepicker To, I've bumped across some questions but couldn't find the answer, so I've tried doing the easiest way I could think of:
Set MaxDate property for datepicker from in form_load event
private void Form1_Load(object sender, EventArgs e)
{
datepickerFrom.MaxDate = datepickerFrom.Value;
}
Then do the same for value_changed event
private void datepickerFrom_ValueChanged(object sender, EventArgs e)
{
datepickerFrom.MaxDate = datepickerFrom.Value;
}
This was easy and fine, only few lines of code, and I've only needed datepickerFrom_ValueChanged event, but recently I've tried typing date into datepicker insted of selecting it, and then all hell broke loose.
So I came to some solution for validation, instead of setting MaxDate property, I've tried this.
private void dtFrom_ValueChanged(object sender, EventArgs e)
{
DateTime from = datepickerFrom.Value;
DateTime to = datepickerTo.Value;
int year= from.Year > to.Year ? to.Year : from.Year;
int month = from.Month > to.Month ? to.Month : from.Month;
int day = from.Day > to.Day ? to.Day : from.Day;
int hour = from.Hour > to.Hour ? to.Hour : from.Hour;
int minute = from.Minute > to.Minute ? to.Minute : from.Minute;
int second = from.Second > to.Second ? to.Second : from.Second;
//setting datepicker value
datepickerFrom.Value = new DateTime(year, month, day, hour, minute, second);
}
This works fine, but feels like bit of headache, and I have to do this for datepickerTO_ValueChanged event also, sure I could make one method and call it two times, but still feels like there is a batter way for this, so any suggestions?
Thank you for your time
Solution 1:
You can handle datePickerTo close event and do something like:
private void dateTimePickerTo_CloseUp(object sender, EventArgs e)
{
DateTime fromdate = Convert.ToDateTime(dateTimePickerFrom.Value);
DateTime todate1 = Convert.ToDateTime(dateTimePickerTo.Value);
if (fromdate > todate1)
//Error
}
You can also use DateTime.Compare whcih get two date
like
int result = DateTime.Compar(dateTimePickerFrom.Value ,dateTimePickerTo.Value);
if result is 1 means From date is earlier, see this link.
Note1:
but as you said if user type in From or To textboxes then closeup event never fire so you need compare them in where you want to process
such as button click.
Note2:
As #Sinatr comment if Value is DateTime then don't need to convert it so the code would be like:
if (dateTimePickerFrom.Value >dateTimePickerTo.Value)
//Error
Your proposal would lead to a horrible interface. Suppose the following case:
From = 1 jan 2000
To = 1 feb 2000
User wants to change both values to 2010. He starts with the from value:
From = 1 jan 2010
Now he wants to change the TO value to 1 feb 2010. Alas, he can't.
Proper usage would be: add some button with which the operator can affirm he has changed all data, start checking it and update. In windows this button is usually named Apply Now or OK. Why deviate from this windows standard.
private void OnFormLoading(object sender, ...)
{
this.FromDate.MinValue = ... // use the real absolute min value you want ever to allow
this.FromDate.MaxValue = ...;
this.ToDate.MinValue = ...;
this.ToDate.MaxValue = ...;
}
Don't do any checking as long as the operator is making changes. Strat checking the input values when he indicates that he finished making changes:
private void OnButtonApplyNow_Clicked(object sender, ...)
{
bool InputOk = CheckInput();
if (!inputOk)
{
ShowIncorrectInput(); // for instance using a MessageBox
}
}

Force a specific day of the week on a datetime

I am writing an asp.net web app where i want a user to be able to select the end of a pay period.
Pay periods always end on a saturday.
I'm using a calender control, and have given it an onSelectionChanged event handler that looks like this:
protected void forceSaturdaySelection (object sender, EventArgs e)
{
Weekending.SelectedDate = Weekending.SelectedDate.AddDays(DayOfWeek.Saturday - Weekending.SelectedDate.DayOfWeek);
}
This code works, as i want the web application to select the end of the pay period the user selects, no matter which day of the week they select.
My question is, is there a more readable way of doing this?
There isn't... but that won't stop you from doing it yourself! Create an extension method.. or simply another method to call:
private DateTime getPayPeriodEnding(DateTime selectedDate) {
return selectedDate.AddDays(DayOfWeek.Saturday - selectedDate.DayOfWeek);
}
Extension method version:
public static DateTime NextPayPeriodEndDate(this DateTime selectedDate) {
return selectedDate.AddDays(DayOfWeek.Saturday - selectedDate.DayOfWeek);
}
Then your code becomes either:
WeekEnding.SelectedDate = getPayPeriodEnding(WeekEnding.SelectedDate);
Or..
WeekEnding.SelectedDate = WeekEnding.SelectedDate.NextPayPeriodEndDate();

How to check if 30 days have passed?

How to check if 30 days have passed since the user has first opened my app? After 30 days have passed, the app should do some things, for example: backup data, send mail etc.
The I would like to reset the 30 day timer to 0, and check again in 30 days.
Yes you can do with the help of IsolatedStorageSettings. You can save first launch date in IsolatedStorageSettings Application_Launching. add following in your App.xaml.cs, May this will help you
private void Application_Launching(object sender, LaunchingEventArgs e)
{
IsolatedStorageSettings userSettings = IsolatedStorageSettings.ApplicationSettings;
//Save first launch date
if (!userSettings.Contains("Date"))
{
userSettings.Add("Date", DateTime.Now.Date);
}
else
{
DateTime saveDate = Convert.ToDateTime(userSettings["Date"]);
double days = (DateTime.Now.Date - saveDate).TotalDays;
if (days > 30)
{
//Do you work
//remove userSettings for reset settings
userSettings.Remove("Date");
}
}
userSettings.Save();
}
You can use IsolatedStorageSettings to store key value pairs. Then on the app startup you can check the value and compare it to todays date and do whatever you want.
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
settings["somekey"] = "myvalue";
settings["otherkey"] = true;
settings.Save();
http://blog.rajenki.com/2013/01/local-and-roaming-storage-on-windows-8-and-windows-phone/
You need to store the start time and date of the 30-day interval in a file using the IsolatedStorage.
The start date must be read when your app is loaded and compared with the current date and time. If that timespan is > 30 days, do your tasks, then store the current date as start of the interval.

using 2 datepickers to display days difference in a textbox

I have 2 datetime pickers and i want to display number of days between them on a text box if a user selects a date.. the problem with my code is that its not giving me correct answers and the time span doesnt seem to work.. i dont know where im going wrong thats why i asked for assistance.
I hope that explained better, please bear with me, its my first time to be on this site so im not familiar with the controls, sending stuff and updating
When i choose different dates it gives me answer 10.999998008713 days instead of 11 days and i dont know if i need to do math roundup
private void btnCalc_Click(object sender, EventArgs e)
{
DateTime start = ArrivalDate.Value;
DateTime finish = DepartureDate.Value;
TimeSpan numberOfNights = finish-start;
double TotalDays= numberOfNights.Days;
txtBoxNum.Text = (numberOfNights.ToString());
}
private void ArrivalDate_ValueChanged(object sender, EventArgs e)
{
DepartureDate.Value = ArrivalDate.Value.AddDays(1);
}
private void DepartureDate_ValueChanged(object sender, EventArgs e)
{
// setting messagebox to a sensible default message if no date or wrong date picked
if (DepartureDate.Value < ArrivalDate.Value)
{
MessageBox.Show("Cannot be less than previous date");
DepartureDate.Value = ArrivalDate.Value.AddDays(1);
}
else
{
double Days = (DepartureDate.Value - ArrivalDate.Value).TotalDays;
txtBoxNum.Text = Days.ToString();
return;
You need to get only the date part from your date picker:
DateTime start = ArrivalDate.Value.Date;
DateTime finish = DepartureDate.Value.Date;
Otherwise you also get time which interferes with your calculations.
Also, to display number of days as integer, use:
int TotalDays = numberOfNights.Days; // Days is int anyway
txtBoxNum.Text = TotalDays.ToString();
Or simply
txtBoxNum.Text = numberOfNights.Days.ToString();
You can actually put the whole code into one line:
txtBoxNum.Text = new TimeSpan(DepartureDate.Value.Date.Ticks - ArrivalDate.Value.Date.Ticks).Days.ToString();

Issue while Retrieving DateTime from session and calculating TimeSpan in ASP.Net using c#.

I am storing Datetime in a session as mentioned below:-
Session["LoggedInTime"] = System.DateTime.Now;
Then i m retrieving this value on a page load like this:-
DateTime _loggedInTime = Convert.ToDateTime(Session["LoggedInTime"]);
I debug the above code code and find that up to here the _loggedInTIme is showing the correct date which i m storing in it. After that i m calculating the time span like this:-
TimeSpan elapsedtimespan = System.DateTime.Now.Subtract(_loggedInTime);
int elapsedtime = Convert.ToInt32(elapsedtimespan.TotalSeconds);
I found while debugging the code that ,while subtraction the _loggedInTime = {1/1/0001 12:00:00 AM} and due to which i m not able to get exact elapsedtime .
Please help me to solve this issue as i m not getting why the _loggedInTime become {1/1/0001 12:00:00 AM} at calculating TimeSpan.
The following works fine for me. Since you prefix _loggedInTime with an underscore I'm assuming you declared it as an instance variable of the page itself.
private DateTime _loggedInTime;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["LoggedInTime"] == null)
Session["LoggedInTime"] = DateTime.Now;
_loggedInTime = Convert.ToDateTime(Session["LoggedInTime"]);
TimeSpan elapsedtimespan = DateTime.Now.Subtract(_loggedInTime);
int elapsedtime = Convert.ToInt32(elapsedtimespan.TotalSeconds);
}
I'm guessing that you are calculating the elapsed time at another time and not in the Page_Load as in the above example.
Make sure that on each post back you correctly load the elapsed time from the session before calculating the elapsed time. On the next post back the _loggedInTime is reset to the default value of a DateTime, being {1/1/0001 12:00:00 AM}.
I think you have something to the following setup.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["LoggedInTime"] == null)
Session["LoggedInTime"] = DateTime.Now;
_loggedInTime = Convert.ToDateTime(Session["LoggedInTime"]);
}
}
private void ButtonClick(object sender, ImageClickEventArgs e)
{
TimeSpan elapsedtimespan = DateTime.Now.Subtract(_loggedInTime);
int elapsedtime = Convert.ToInt32(elapsedtimespan.TotalSeconds);
}
Here I demonstrate it by handling a postback when a button is clicked. In that case the Page_Load does not load the LoggedInTime and the elapsed time is calculated incorrectly. To solve this, just remove the IsPostBack if statement in the Page_Load. Make sure you set the instance variable _loggedInTime each time you load the page, thus also on a postback.
Remark: Also check if you are on a server farm. If you are using multiple servers to handle your requests but have configured the wrong session mode (e.g. in process) then server A will store the session variable in its memory, but the redirect can be handled by server B, which doesn't know about server A's in-memory session store.
More information can be found on MSDN:
Session-State Modes
In process session state is the default, in a server farm scenario you can use the StateServer or SqlServer alternatives to share session state between the servers. Or you can write your own custom session state provider.
Since that's the default value for DateTime, I'm guessing you're attempting to use loggedInTime when it was not previously initialized in the Session object. In other words, my suggestion is to try something along these lines:
int elapsedtime = 0;
if (Session["LoggedInTime"] != null)
{
DateTime _loggedInTime = (DateTime)Session["LoggedInTime"];
TimeSpan elapsedtimespan = System.DateTime.Now.Subtract(_loggedInTime);
elapsedtime = Convert.ToInt32(elapsedtimespan.TotalSeconds);
}
else Session["LoggedInTime"] = System.DateTime.Now;

Categories

Resources