将日期和时间的字符串表示形式转换为System.DateTime

时间:2010-12-14 20:13:47

标签: c# datetime

DateTime dt;
bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.AssumeLocal, out dt);

diditParse返回false,因为它期望的格式MM/DD/YYYY与我的格式不同DD/MM/YYYY

我不确定哪些文化/样式或需要做什么才能使try解析工作?

5 个答案:

答案 0 :(得分:4)

如果你看一下这里给出的例子http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx 你可以使用:

bool diditParse = DateTime.TryParse("17/06/2000 12:00:00 AM", out dt);

除非你寻找更深入的东西,否则你不需要使用文化/风格部分。

您尝试使用http://msdn.microsoft.com/en-us/library/9h21f14e.aspx

public static bool TryParse(
string s,
IFormatProvider provider,
DateTimeStyles styles,
out DateTime result
)

Parameters

s
Type: System.String
A string containing a date and time to convert. 
provider
Type: System.IFormatProvider
An object that supplies culture-specific formatting information about s. 
styles
Type: System.Globalization.DateTimeStyles
A bitwise combination of enumeration values that defines how to interpret the parsed date in relation to the current time zone or the current date. A typical value to specify is None.
result
Type: System.DateTime%
When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uni

答案 1 :(得分:3)

如果您知道该字符串是DD / MM / YY格式,那么您可以使用TryParseExact

答案 2 :(得分:1)

尝试使用DateTime.TryParseExact()

它似乎允许您告诉它期望的日期格式。

答案 3 :(得分:0)

...试

("fr-FR") 

尽管以这种方式表示日期的任何欧洲或其他文化都应该有用。

答案 4 :(得分:0)

尝试“en-GB”我们列出我们的日期DD-MM-YY,而不是像在美国那样列出MM-DD-YY。