var data = "15:00";
if (TimeSpan.TryParse(data, out var time))
{
Console.WriteLine("Time: {0}", time);
}
else if (DateTime.TryParse(data, out var datetime))
{
Console.WriteLine("DateTime: {0}", datetime);
}
else
{
Console.WriteLine("I don't know how to parse {0}", data);
}
0
如果我有一个像“15:00”这样的字符串并将其解析为DateTime ot DateTimeOffset,则日期设置为今天 .
var hours = "15:00";
var date = DateTime.Parse(hours, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault);
// 1/1/0001 3:00:00 PM
但我认为你的问题仍然存在; "if the date part is given or not.."你是如何决定你的字符串是否有日期部分的? Steve commented总是有5个字符吗?它可以采用 4:00 格式? 4:1 怎么样?如果它可以像 4:1 那样,应该解析为 4:10 或 4:01 ?
因此,您需要先确定"if the date part is given or not.."的含义是什么意思 . 然后你可以轻松地将你的字符串解析为 TimeSpan ,而不是 DateTime ,所以,你可以用 DateTime(int, int, int) 构造函数手动创建"1.1.1970" .
if(YourConditionForYourStringNotIncludingDatePart)
{
var time = TimeSpan.Parse("15:00");
var date = new DateTime(1970, 1, 1);
var result = date.Add(time);
}
3 回答
尝试将值解析为
TimeSpan
,然后尝试将其解析为DateTime
.这是设计的 .
从DateTime.Parse doc:
从DateTimeOffset.Parse doc:
因此,对于
DateTime
,如果您不使用任何DateTimeStyles
,则会获得当前日期但如果你使用
DateTimeStyles.NoCurrentDateDefault
作为第三个参数;但我认为你的问题仍然存在; "if the date part is given or not.."你是如何决定你的字符串是否有日期部分的? Steve commented总是有5个字符吗?它可以采用
4:00
格式?4:1
怎么样?如果它可以像4:1
那样,应该解析为4:10
或4:01
?因此,您需要先确定"if the date part is given or not.."的含义是什么意思 . 然后你可以轻松地将你的字符串解析为
TimeSpan
,而不是DateTime
,所以,你可以用DateTime(int, int, int)
构造函数手动创建"1.1.1970" .使用常规expressins进行DateTime解析通常是个坏主意 . 我不建议使用它,除非你没有其他方法为DateTime这样做 .
我认为对于那种情况你可以保持简单 . 当只有一个时间段时,这可能是一个不依赖于长度的解决方案:
输出:
取决于您的本地化:-)