[英]Datetime.TryParse can't parse yyyy/MM/dd format
I am at the moment trying to convert a date given in the format as yyyy/MM/dd
. 我目前正在尝试转换以yyyy/MM/dd
格式给出的日期。 To check if a valid Date is given. 检查是否给出了有效的日期。
if(!DateTime.TryParse(textBoxDatumVanStorting.Text, out Test2))
Is what im using at the moment but it always gives me a wrong date. 我目前正在使用什么,但它总是给我一个错误的日期。
I have Looked in to using DateTime.TryParseExact
. 我一直在寻找使用DateTime.TryParseExact
。 But cant seem to get this to work. 但是似乎无法使它正常工作。
Specifying a Format 指定格式
Consider using the DateTime.TryParseExact()
method which will allow you to explicitly define the format your string is in : 考虑使用DateTime.TryParseExact()
方法,该方法将允许您显式定义字符串的格式:
// This will attempt to parse your date in exactly the format provided
if(!DateTime.TryParseExact(textBoxDatumVanStorting.Text,"yyyy/MM/dd", null, DateTimeStyles.None, out Date2))
{
// Your date is not valid, consider doing something
}
A Matter of Culture 文化问题
In the above example, the third parameter being passed in represents the specific culture / format that you expect to use to parse the date. 在上面的示例中,传入的第三个参数表示您希望用来解析日期的特定区域性/格式。 Using null
will default to the current culture, but if you need to explicitly specify this, you can do so here as seen using the invariant culture : 使用null
将默认为当前区域性,但是如果您需要显式指定它,则可以在此处使用不变区域性进行显示:
Date output;
if(!DateTime.TryParseExact(input,"yyyy/MM/dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out output))
{
// Uh oh again...
}
If DateTime.TryParse
can't parse your string, that means this yyyy/MM/dd
format is not a standard date format for your CurrentCulture
. 如果DateTime.TryParse
无法解析您的字符串,则意味着yyyy/MM/dd
格式不是CurrentCulture
的标准日期格式。
You can use DateTime.TryParseExact
with custom format like; 您可以将DateTime.TryParseExact
与以下自定义格式一起使用:
DateTime Test2;
if (DateTime.TryParseExact(textBoxDatumVanStorting.Text, "yyyy/MM/dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out Test2))
{
// Successfull parse
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.