C# 将格式为12小时(2013年4月29日上午10:00:00)的字符串转换为C中的日期时间#
我正在从我的config.xml中检索这样的字符串(2013年4月29日上午10:00:00)。我想将其转换为DateTime格式。如何执行此操作 我尝试了以下几点:C# 将格式为12小时(2013年4月29日上午10:00:00)的字符串转换为C中的日期时间#,c#,string,c#-4.0,datetime,service,C#,String,C# 4.0,Datetime,Service,我正在从我的config.xml中检索这样的字符串(2013年4月29日上午10:00:00)。我想将其转换为DateTime格式。如何执行此操作 我尝试了以下几点: DateTime dtNextrunTimeforExcel = Convert.ToDateTime(str); 及 但是,在这两种情况下,它都表示“字符串未被识别为有效的日期时间” 注意:我正在用VS2010编写Windows服务 Pl.帮助。尝试使用.ParseExact var dtNextrunTimeforExce
DateTime dtNextrunTimeforExcel = Convert.ToDateTime(str);
及
但是,在这两种情况下,它都表示“字符串未被识别为有效的日期时间”
注意:我正在用VS2010编写Windows服务
Pl.帮助。尝试使用
.ParseExact
var dtNextrunTimeforExcel = DateTime.ParseExact(str, "MM/dd/yyyy hh:mm:ss", CultureInfo.CurrentCulture);
尝试使用
.ParseExact
var dtNextrunTimeforExcel = DateTime.ParseExact(str, "MM/dd/yyyy hh:mm:ss", CultureInfo.CurrentCulture);
我已经修改了我的问题。一旦得到日期时间,我会将其与当前日期时间进行比较。那么,Var是否有效?@bapirout-它将返回一个日期时间。var是强类型的,在本例中相当于
DateTime dtNextrunTimeforExcel
。所以它会起作用。您没有考虑AM/PM…如果我使用AM/PM,我会得到相同的错误。@bapirout-所以只需调整在分析字符串中包含AM/PM。我已经修改了我的问题。一旦得到日期时间,我会将其与当前日期时间进行比较。那么,Var会起作用吗?@bapirout-它将返回日期时间。var是强类型的,在本例中相当于DateTime dtNextrunTimeforExcel
。所以它会起作用。您没有考虑AM/PM…如果我使用AM/PM,我会得到相同的错误。@bapirout-所以只需调整在解析字符串中包含AM/PM即可。
CultureInfo enUS = new CultureInfo("en-US");
string dateString;
DateTime dateValue;
// Parse a string.
dateString = "4/29/2013 10:00:00 AM";
if (DateTime.TryParseExact(dateString, "mm/dd/yyyy hh:mm:ss tt", enUS,
DateTimeStyles.None, out dateValue))
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
dateValue.Kind);
///time only
dateString = "10:00:00 AM";
if (DateTime.TryParseExact(dateString, "hh:mm:ss tt", enUS,
DateTimeStyles.None, out dateValue))
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
dateValue.Kind);