这听起来很傻但我无法将字符串转换为带有日期和时间的DateTime
我试试这个:
Response.Write(year + " " + month + " " + day + " " + hour + " " + min );
//prints 2008 9 23 11 59 0 (represents 9/23/2008 11:59 00 AM)
DateTime dt= new DateTime(year , month , day , hour , min , 00);
但它告诉我它不是可表示的DateTime。这里也是一样。
String toParse = "9/23/2008" + " " + hour + ":" + minute + " 00 " + "AM" ;
DateTime dt= Convert.ToDateTime(toParse);
我遇到了这么多麻烦。我该如何正确地做到这一点?
答案 0 :(得分:2)
我认为你的问题在这里
+ minute + " 00 " + "AM"
应该是:
+ minute + ":00 " + "AM"
答案 1 :(得分:0)
Check this link for more info:-
http://msdn.microsoft.com/en-us/library/9xk1h71t.aspx
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
Console.WriteLine("{0,-18}{1,-12}{2}\n", "Date String", "Culture", "Result");
string[] cultureNames = { "en-US", "ru-RU","ja-JP" };
string[] dateStrings = { "01/02/09", "2009/02/03", "01/2009/03",
"01/02/2009", "21/02/09", "01/22/09",
"01/02/23" };
// Iterate each culture name in the array.
foreach (string cultureName in cultureNames)
{
CultureInfo culture = new CultureInfo(cultureName);
// Parse each date using the designated culture.
foreach (string dateStr in dateStrings)
{
DateTime dateTimeValue;
try {
dateTimeValue = Convert.ToDateTime(dateStr, culture);
// Display the date and time in a fixed format.
Console.WriteLine("{0,-18}{1,-12}{2:yyyy-MMM-dd}",
dateStr, cultureName, dateTimeValue);
}
catch (FormatException e) {
Console.WriteLine("{0,-18}{1,-12}{2}",
dateStr, cultureName, e.GetType().Name);
}
}
Console.WriteLine();
}
}
}