简体   繁体   中英

Convert String to DateTime Object and Add it to total time

I have string list which contains spent time in hh:mm:ss as string like

00:00:40
00:01:00
00:02:10

I want to add these values and show it to user as

Total Time: 00:03:50

I can parse each time value to date time but how can I add them to show the result show above.

Here is how I am parsing the string to DateTime

foreach(string itm in TimeList)
{
    DateTime sTime = DateTime.ParseExact(itm , "HH:mm:ss", CultureInfo.CurrentCulture);
}

Your parsing operation is fine. But you assign the result to your sTime in every iteration, that's why you lost all of the data except the last one.

But more important, instead of DateTime , I would parse them to TimeSpan instead which fits better to your data since it is a time interval .

var list = new List<string>
{
    "00:00:40",
    "00:01:00",
    "00:02:10"
};

var total = TimeSpan.Zero;

foreach (var item in list)
{
    total += TimeSpan.ParseExact(item, "hh\\:mm\\:ss", CultureInfo.InvariantCulture);
}

Now you can format your total and show to user like;

string.Format("Total Time: {0}", 
               total.ToString("hh\\:mm\\:ss", CultureInfo.InvariantCulture));

It seems ParseExact is not available in DotNet 3.5

Then you can use TimeSpan.Parse method which is available since .NET 1.0 version. But I strongly suggest to you consider to upgrade your framework version if you can.

foreach (var item in list)
{
    total += TimeSpan.Parse(item);
}

You should use TimeSpan , not DateTime , since 00:00:40 means 40 seconds and not 40 seconds after midnight . You can use Linq to sum up the values:

List<String> times = new List<String>() {
  "00:00:40",
  "00:01:00",
  "00:02:10"};

var totalTime = new TimeSpan(times
  .Select(item => TimeSpan.Parse(item).Ticks)
  .Sum());

// 00:03:50
Console.Write("Total Time: {0}", totalTime); 

Try doing it this way:

var TimeList = new [] { "00:00:40", "00:01:00", "00:02:10" };

var TotalTime =
    TimeList
        .Select(itm => TimeSpan.Parse(itm))
        .Aggregate((ts0, ts1) => ts1.Add(ts0));

Console.WriteLine("Total Time: {0}", TotalTime);

That gives me:

Total Time: 00:03:50

You can use TimeSpan as storage

var spent = TimeSpan.FromTicks(TimeList.Sum(i => TimeSpan.Parse(i).Ticks));

Then print the spent as the format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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