Reputation: 93
I am creating a reminder to match the date and time from user input. I can get the current date and time by using a Timer
and ScriptManager
. But I have no idea on how I should compare the date and time with the user input and make the label below visible after they are matched. Any ideas?
Here is my code:
public partial class Reminder : System.Web.UI.Page
{
private void UpdateTimer()
{
LabelCurrentTime.Text = System.DateTime.Now.ToLongTimeString();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
UpdateTimer();
}
protected void Button1_Click(object sender, EventArgs e)
{
string currentdate = LabelCurrentDate.Text;
string currenttime = LabelCurrentTime.Text;
string reminderdate = TextBoxReminderDate.Text;
string remindertime = TextBoxReminderTime.Text;
Timer1.Enabled = true;
LabelCurrentTime.Text = System.DateTime.Now.ToLongTimeString();
LabelCurrentDate.Text = System.DateTime.Now.Date.ToShortDateString();
if (currentdate == reminderdate)
{
if (currenttime == remindertime)
{
Label1.Visible = true;
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Timer1.Enabled = false;
}
}
Here is the screenshot : screenshot
Upvotes: 0
Views: 1953
Reputation: 8659
Parse your date and time like this:
var dt = DateTime.Parse(currentDate+" "+currentTime);
var dt2 = DateTime.Parse(reminderDate+" "+reminderTime);
Then you use the DateTime.Compare method to compare your DateTime objects.
Consider the following:
var val = DateTime.Compare(dt,dt2);
If val is 0 the dates and times are the same. If val is more than 0, currentDate has passed reminderDate and if val is less than zero, currentDate is before reminderDate.
Upvotes: 1
Reputation: 203821
You're trying to deal with dates as strings. You shouldn't do that.
First off, you shouldn't accept the date as user input from a Textbox
. There's a specific DateTimePicker
control specifically for having a user select a date. You should use that.
If you use the date picker for the user to provide a date then you can get the current date using DateTime.Now
. Now that you have two real dates you can compare them using the >
operator.
Upvotes: 3