Comparing date and time
I want to write an alarm clock application that should display a certain message at a time set by the user.
How to compare system date and time wi开发者_如何学Cth the time set by users in a text box? Thanks FurqanYou can convert TextBox.Text
value to a DateTime
value as the following:
String dateTimeFormat = "MM/dd/yyyy hh:mm:ss tt";
DateTime dateTimeValue =
DateTime.ParseExact(textBox.Text, dateTimeFormat ,
CultureInfo.InvariantCulture);
DateTime.ParseExact Method converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly or an exception is thrown.
You should use the intellisense feature ... but the hint is:
DateTime.Parse
....
and you need a timer, I called him "timEr" (you should name him better ....), and read the answer from Akram, he made it culture independent ....
Private Sub timEr_Tick(sender As System.Object, e As System.EventArgs) _
Handles timEr.Tick
timEr.Enabled = False
If DateTime.Now >= DateTime.Parse("29.06.2011 17:29") Then
MessageBox.Show("Time to leave the office ....")
End If
End Sub
Your best bet would be to use System.DateTime
object
Just make sure when you take a users input from a text box, that you save it in a DateTime
object, then you can use the generic DateTime.Equals
to compare the two.
Dim currentDateTime As New System.DateTime
Dim alarmDateTime As DateTime
currentDateTime = Date.Now
alarmDateTime =
New DateTime(2011, Month(Date.Now), dayInput, hourInput, minuteInput, 0)
If currentDateTime.Equals(alarmDateTime) Then
'alarm code
End If
Something to this effect shold get the job done.
EDIT: The parse method outlined in one of the other solutions would be better for creating your alarmDateTime object than manually doing it.
Since you're using VB.NET you can use the functionality in Microsoft.VisualBasic.DateAndTime
. For example, you could use DateTime.Parse
(or better, .TryParse
) to get a DateTime
representation of the user's value, then check whether the system time is within, say, one minute of the user's time. This way, you don't need to mess with seconds.
Dim diffInMinutes As Long =
Microsoft.VisualBasic.DateAndTime.
DateDiff(DateInterval.Minute, userTime, DateTime.Now)
精彩评论