Reputation: 445
I have a textBox where the user enters a datetime using a calendar, I am checking for whether the text box is empty or not by
if ((string.IsNullOrEmpty(txt_SendAt.Text) == false)
How can I check whether the datetime entered is less or = to the current datetime
Upvotes: 0
Views: 594
Reputation: 11916
if (!(string.IsNullOrEmpty(txt_SendAt.Text) && Datetime.Parse(txt_SendAt.Text)<=Datetime.Now)
{
/*code */
}
else
{
/*code */
}
Upvotes: 0
Reputation: 498992
Use one of the Parse
or TryParse
static methods of the DateTime
class to convert the string to a DateTime
and compare it to the current DateTime.
DateTime input;
if(DateTime.TryParse(txt_SendAt.Text,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out input))
{
if(input <= DateTime.Now)
{
// your code here
}
}
else
{
//not a valid DateTime string
}
Upvotes: 0
Reputation: 8226
You can parse your string input to a DateTime
using the DateTime.Parse
method, then run your comparison in the normal way.
Remember, Parse
methods will throw a FormatException
if the input is not directly castable to the required type. It may make more sense to go for the TryParse method if you have, for example, a free-text input.
var inputDate = DateTime.Parse(txt_SendAt.Text);
if (inputDate > DateTime.Now)
{
Console.WriteLine("DateTime entered is after now.");
}
else if (inputDate < DateTime.Now)
{
Console.WriteLine("DateTime entered is before now.");
}
Upvotes: 0
Reputation: 45083
A few steps here, first check something is entered, as you have done, secondly, check it is actually a date, and lastly check against the desired date, as such:
var input = DateTextBox.Text;
if (!string.IsNullOrEmpty(input))
{
DateTime date;
if (DateTime.TryParse(input, out date))
{
if (date <= DateTime.Now)
{
//bingo!
}
}
}
Notice the TryParse
for checking proper formatting of the input string as a date - using only Parse
is a sure way to make your app go BANG!
Upvotes: 0
Reputation: 62504
DateTime enteredDateTime;
if (!DateTime.TryParse(txt_SendAt.Text, out enteredDateTime))
{
Debug.WriteLine("User entered date time in wrong format");
}else
{
if(enteredDateTime <= DateTime.Now)
{
// less or equal
}
}
Upvotes: 1
Reputation: 51634
Parse
or TryParse
the text to DateTime
, then compare to DateTime.Now
Upvotes: 0
Reputation: 108957
if ((string.IsNullOrEmpty(txt_SendAt.Text) == false
&& DateTime.Parse(txt_SendAt.Text) <= DateTime.Now )
Upvotes: 1