[英]how to Check datetime entered
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 我有一个textBox,用户使用日历输入日期时间,我正在检查文本框是否为空
if ((string.IsNullOrEmpty(txt_SendAt.Text) == false)
How can I check whether the datetime entered is less or = to the current datetime 如何检查输入的日期时间是否小于或=当前日期时间
if ((string.IsNullOrEmpty(txt_SendAt.Text) == false
&& DateTime.Parse(txt_SendAt.Text) <= DateTime.Now )
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
}
}
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
类的Parse
或TryParse
静态方法之一将字符串转换为DateTime
并将其与当前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
}
将文本Parse
或TryParse
到DateTime
,然后与DateTime.Now
进行比较
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! 注意
TryParse
用于检查输入字符串的正确格式作为日期 - 仅使用Parse
是使您的应用程序变为BANG的可靠方法!
You can parse your string input to a DateTime
using the DateTime.Parse
method, then run your comparison in the normal way. 你可以分析你的字符串输入到
DateTime
使用DateTime.Parse
方法,然后运行在正常方式的比较。
Remember, Parse
methods will throw a FormatException
if the input is not directly castable to the required type. 请记住,如果输入不能直接转换为所需类型,则
Parse
方法将抛出FormatException
。 It may make more sense to go for the TryParse method if you have, for example, a free-text input. 如果你有一个自由文本输入,那么去TryParse方法可能更有意义。
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.");
}
if (!(string.IsNullOrEmpty(txt_SendAt.Text) && Datetime.Parse(txt_SendAt.Text)<=Datetime.Now)
{
/*code */
}
else
{
/*code */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.