繁体   English   中英

通用字符串拆分难题/字符串C#中的时间

[英]General String splitting Conundrums / Times from Strings C#

这个问题更多的是开放式的,什么是最佳实践,或者您认为什么是最佳实践方案? 我试图获得两次,将它们的数字分开,以便可以将它们放入DateTime值中。

我认为是最快,最干净的示例,但我不确定...

string a = "11:50-12:30";
a = Regex.Replace(a, @"[^\d]", ""); //output 11501230
string time_1 = a.Substring(0, 3);
string time_2 = a.Substring(4, 7);
// DO SOME parsing of strings to ints
DateTime Start = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, //enter some separate ints here)

但是也许我可以做些类似的事情? 而且这不能慢很多吗? 也许更快?

string a = "11:50-12:30"
string a_1 = a.substring(0,4);
string b = DateTime.Today.Year.toString() + DateTime.Today.Month.toString() + DateTime.Today.Day.toString() + "11:50-12:30";
DateTime mytime = DateTime.ParseExact(a_1, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

与效率无关,但:由于您主要关注时间,为什么不将每个部分解析为System.TimeSpan ,然后如果您希望将其表示一个时刻,则可以将其添加到DateTime实例中(使用Add )。

string a = "11:50-12:30";
var parts = a.Split('-');
var time_1 = TimeSpan.Parse(parts[0]);
var time_2 = TimeSpan.Parse(parts[1]);
var start = DateTime.Today.Add(time_1);
var end = DateTime.Today.Add(time_2);

我省略了对Split调用进行检查以检查是否有2个部分以及在Parse上进行错误检查的建议。 您也可以使用TryParse,但您知道了。

您可以使用System.Diagnostics中的Stopwatch手动测试性能

    string a = "11:50-12:30";

    Stopwatch watch = new Stopwatch();
    watch.Start();
    DateTime start = DateTime.Today.Add(DateTime.ParseExact(a.Split('-').First(), "hh:mm", CultureInfo.InvariantCulture).TimeOfDay);
    DateTime end = DateTime.Today.Add(DateTime.ParseExact(a.Split('-').Last(), "hh:mm", CultureInfo.InvariantCulture).TimeOfDay);
    watch.Stop();
    Console.WriteLine(watch.Elapsed.ToString());
    Console.WriteLine(start.ToString());
    Console.WriteLine(end.ToString());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM