简体   繁体   English

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

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

This question is more an open ended what is best practice, or what do you do think is good practice scenario ? 这个问题更多的是开放式的,什么是最佳实践,或者您认为什么是最佳实践方案? I'm trying to get two times, separate out their numbers so they can be placed into a DateTime value. 我试图获得两次,将它们的数字分开,以便可以将它们放入DateTime值中。

Example which I think is the quickest and cleanest but I am not sure... 我认为是最快,最干净的示例,但我不确定...

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)

But perhaps I can do something like ? 但是也许我可以做些类似的事情? and this can't be signifcantly slower can it ? 而且这不能慢很多吗? perhaps its quicker? 也许更快?

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);

Nothing to do with efficiency but: As you are primarily concerned with times why not parse each part to a System.TimeSpan and that could then be added to a DateTime instance (using Add ) if you want it to represent a moment in time. 与效率无关,但:由于您主要关注时间,为什么不将每个部分解析为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);

I omitted error checking on the Split call to check that there are 2 parts and also on Parse which would be advisable. 我省略了对Split调用进行检查以检查是否有2个部分以及在Parse上进行错误检查的建议。 You could also use TryParse but you get the idea. 您也可以使用TryParse,但您知道了。

You can test performance manually using Stopwatch from System.Diagnostics 您可以使用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