我需要用 HH:MM:SS + 当前日期创建一个 DateTime
string myTime = "08:50:00";
DateTime currentDateTime = DateTime.UtcNow.date;
结果应该是结合了这些信息的 DateTime。怎么做 ?
您需要使用ParseExact
- http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
所以:
var provider = CultureInfo.InvariantCulture;
var date = DateTime.ParseExact(myTime,"hh:mm:ss",provider);
它应该使用当前日期作为日期部分。
这是你想要的吗:
DateTime dateTime = DateTime.Today + TimeSpan.Parse(myTime);
string myDateTimeString;
DateTime dt;
dt = Convert.ToDateTime(myDateTimeString);
Response.Write(dt.Day + "/" + dt.Month + "/" + dt.Year);
见http://www.ezineasp.net/post/C-Convert-String-to-DateTime.aspx
你可以尝试类似的东西
const string myTime = "08:50:00";
DateTime now = DateTime.Now;
string[] split = myTime.Split(':');
DateTime dt = new DateTime(now.Year, now.Month, now.Day, int.Parse(split[0]), int.Parse(split[1]), int.Parse(split[2]));
但是您应该添加一些空值检查和其他验证。
string myTime = "08:50:00";
DateTime currentDateTime = DateTime.UtcNow.Date;
string myDateTime = string.Format("{0}-{1}-{2} {3}", currentDateTime.Year, currentDateTime.Month, currentDateTime.Day,
myTime);
DateTime dt = Convert.ToDateTime(myDateTime, new CultureInfo("en-GB"));
//or
DateTime myNewDatetime = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day,
8, 50, 0);