说我有以下内容:
string fromTime = "8:00am";
string someDate = "06/01/2012";
我想最终这样做:
DateTime dt = Convert.ToDateTime(someDate + someTime);
基本上我想约会并添加时间到上面的结果是
06/01/2012 8:00am
但将其存储在日期时间变量中。这可能吗?
您可以使用DateTime.TryParseExact方法,该方法允许您在解析时指定格式:
class Program
{
static void Main()
{
string s = "06/01/2012 8:00am";
string format = "dd/MM/yyyy h:mmtt";
DateTime date;
if (DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
Console.WriteLine(date);
}
}
}
试试这个:
DateTime dt = DateTime.ParseExact(someDate + " " + someTime, "MM/dd/yyyy h:mmtt", CultureInfo.InvariantCulture);