我面临一个小问题,尝试了很多事情后我无法解决,所以它就去了.....页面上有一个文本框,我在其中输入日期,并且我希望该日期在datetime对象中。
例如:日期输入:6 05 2020(dd / MM / yyyy)应该以相同的格式在日期时间对象中访问,但它已更改为(6.05.2020ie:MM / dd / yyyy格式)。
我希望我在这里有意义,我想要的只是这样的东西.....
DateTime dt = convert.ToDateTime(txtDate.Text);
dt应该是(11/2/2010而不是2/11/2010)
@使用以下代码后可能出现
DateTime sDate, eDate = new DateTime();
//修改日期以供我们使用。DateTime.TryParseExact(txtFrom.Text,“ dd / MM / yyyy”,CultureInfo.InvariantCulture,DateTimeStyles.None,超出sDate);
DateTime.TryParseExact(txtFrom.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out eDate);
我得到的日期和日期是6 05 2020 12:00:00 AM,应该是6/05/2020
编辑:此值:“ 11/2/2010”与格式“ dd / MM / yyyy”不匹配。它与格式“ d / M / yyyy”匹配-对于“ dd / MM / yyyy”,应为“ 11/02/2010”。
这就是TryParseExact
为您失败的原因。您需要选择正确的格式模式。
DateTime
值没有格式。它仅表示日期和时间(在ISO日历中,可能在不同的时区中,但这是不同的事情)。就像int
-它不代表“十进制整数”或“十六进制整数”-只是特定范围内的整数。您可以format数字为十进制或十六进制,但是它本身没有格式。
听起来您应该在转换from文本框或可能是ParseExact
时,用TryParseExact
解析它以指定格式,
TryParseExact
出于所有目的,您都应将该值保留为// This is assuming you're absolutely sure of the format used. This is *not*
// necessarily the user's preferred format. You should think about where your
// data is coming from.
DateTime date;
if (DateTime.TryParseExact(text, "dd/MM/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out date))
{
// Okay, successful parse. We now have the date. Use it, avoiding formatting
// it back to a string for as long as possible.
}
except并返回给用户-此时,您最好使用他们的文化设置。
特别是如果您将值存储在数据库中,则不应将其转换为文本并将其包含在SQL语句中-这很麻烦。相反,请使用参数化的SQL语句并将其设置为参数值,仍然设置为DateTime
。
[DateTime
不会以任何特定格式存储日期-它使用内部表示(完全没关系)。
将字符串解析为DateTime
后,那里没有固有的格式。当您输出值时,只有一种格式。您在调试器中看到的只是使用系统设置到字符串的转换。
如果要格式化DateTime
,请使用DateTime
和格式字符串:
ToString
相反也适用-如果您需要明确解析字符串,请使用dt.ToString("dd/MM/yyyy");
或ParseExact
(TryParseExact
的静态成员):
DateTime
阅读有关DateTime dt;
if(DateTime.TryParseExact(txtDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.None, out td))
{
// Valid date used in `txtDate.Text`, use dt now.
}
和custom日期和时间格式的字符串。
为了避免在解析日期时的月/日出现任何错误,使用standard可能比DateTime.Parse or DateTime.ParseExact更好。
如ToDateTime
和this thread所指出。
尝试使用适当的格式提供程序尝试DateTime.Parse。您的情况应该是
this article
如果要使用给定的特定格式访问它,则应使用DateTime.ToString(字符串格式)。
IFormatProvider culture = new CultureInfo("de-DE", true);
DateTime.Parse(txtDate.Text, culture );