How to Convert String "07:35" (Hh:Mm) to Timespan

How to Convert string 07:35 (HH:MM) to TimeSpan

While correct that this will work:

TimeSpan time = TimeSpan.Parse("07:35");

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
// handle validation error
}

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// handle validation error
}
TimeSpan time = dt.TimeOfDay;

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

What is the best way to convert this format to timespan?

Assuming you have a string called value containing such value, you can do

https://msdn.microsoft.com/en-us/library/dd992370(v=vs.110).aspx

TimeSpan timeSpan = TimeSpan.ParseExact(value,@"dd\.hh\.mm\:ss",System.Globalization.CultureInfo.InvariantCulture)

From there, you can use timeSpan.TotalSeconds or timeSpan.TotalHours;

Parse string to TimeSpan

This seems to work, though it is a bit hackish:

TimeSpan span;

if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span))
MessageBox.Show(span.ToString());

How to parse string with hours greater than 24 to TimeSpan?

If you're certain that the format will always be "HH:mm" then try something like this:

string span = "35:15";
TimeSpan ts = new TimeSpan(int.Parse(span.Split(':')[0]), // hours
int.Parse(span.Split(':')[1]), // minutes
0); // seconds

Converting TimeSpan to hh:mm higher than 23:59

You won't be able to format a TimeSpan object via .ToString(format) overload the way you'd like.

Look at Microsoft doc, hh format cannot exceed 23 :

hh The number of hours, which ranges from "00" to "23".

You will have to build the format you want using .TotalHours.

What about:

var ts = new TimeSpan(hours: 50, minutes: 10, seconds: 20);
var hours = Math.Truncate(ts.TotalHours);
var formatted = $"{hours}:{ts.Minutes}:{ts.Seconds}";
Console.WriteLine(formatted); // Display 50:10:20

You could even create an extension method.

LINQ (C#) Sum a String in a HH:mm format

Here you have to use the combinaison of 2 things:

  1. Convert the string into an usable format, that's TimeSpan

    using How to Convert string “07:35” (HH:MM) to TimeSpan

  2. The Sum the TimeSpan using Sum of TimeSpans in C#

public class Toto
{
public int ProjectID { get; set; }
public string ProjectTime { get; set; }
}
static void Main(string[] args)
{
var tmpList = new[]{
new Toto{ProjectID=1, ProjectTime="00:10" },
new Toto{ProjectID=2, ProjectTime="23:20" },
new Toto{ProjectID=2, ProjectTime="23:30" },
new Toto{ProjectID=1, ProjectTime="00:40" },
};

var overviewList = tmpList.GroupBy(x => x.ProjectID)
.Select(x => new
{
ProjectID = x.Key,
ProjectTime = new TimeSpan(x.Sum(o => TimeSpan.Parse(o.ProjectTime).Ticks))
});

Result:

ProjectID =1, ProjectTime=00:50:00

ProjectID =2, ProjectTime=1.22:50:00

That 1.22:50:00 May not be the format you expected. But Timespan Custom format won't be usefull here.

If you need to get the same string format again. You can use, but keep the format TimeSpan as long as you use it use that only for display.

 (int)X.ProjectTime.TotalHours +":" +X.ProjectTime.Minutes

ProjectID =1, ProjectTime=0:50

ProjectID =2, ProjectTime=46:50

C# Convert Liststring to ListTimeSpan

Should do the job:

 var appointmentStartTimes = new List<string>{"7:45", "0:0","a"};

var appointmentStartTimesConverted = appointmentStartTimes
.Select(i =>
{
TimeSpan result;
if(TimeSpan.TryParse(i, out result))
return new Nullable<TimeSpan>(result);
return null;
})
.Where(x => x.HasValue)
.ToList();

Cannot implicitly convert DateTime to Timespan

Based on your input that dr[4] represents time values in hours:minutes:seconds format I recommend following solution.

private TimeSpan GetTimeSpan(string timeString)
{
var timeValues = timeString.Split(new char[] { ':' });
//Assuming that timeValues array will have 3 elements.
var timeSpan = new TimeSpan(Convert.ToInt32(timeValues[0]), Convert.ToInt32(timeValues[1]), Convert.ToInt32(timeValues[2]));
return timeSpan;
}

Use above method as following.

else if (textBox3.Text.Contains("GEN_EX"))
{
foreach (DataTable dt in result.Tables)
{
foreach (DataRow dr in dt.Rows)
{
GEN_EX addtable = new GEN_EX()
{

EX_ID = Convert.ToByte(dr[0]),
DOC_ID = Convert.ToByte(dr[1]),
PATIENT_NO = Convert.ToByte(dr[2]),
TEST_DATE = Convert.ToDateTime(dr[3]),
**TEST_TIME = GetTimeSpan(dr[4].ToString()),**

};
conn.GEN_EXs.InsertOnSubmit(addtable);
}
}
conn.SubmitChanges();
MessageBox.Show("File uploaded successfully");
}

This should give your the value you want. You will face runtime issues if value of dr[4] is not in hours:minutes:seconds format. That I will leave it up to you.



Related Topics



Leave a reply



Submit