How do I add times in C#? For example:
Time = "14:20 pm" + "00:30 pm"
How do I add times in C#? For example:
Time = "14:20 pm" + "00:30 pm"
I have insufficient reputation to add a comment - What do you expect the answer to that to be? 00:30pm isn't even a valid time - it would be 00:30am or 12:30pm
Assuming you want to add 30 minutes to a given DateTime, you can use AddMinutes.
TestTime.AddMinutes(30);
Another way of doing it:
DateTime TestTime = DateTime.Parse("22 Jun 2009 14:20:00");
// Add 30 minutes
TestTime = TestTime + TimeSpan.Parse("00:30:00");
TimeSpan t1 = new TimeSpan(14, 20,0);
TimeSpan t2 = new TimeSpan(0,30,0);
Console.Out.WriteLine(t1 + t2);
You can't add those, just like you can't add "14:20PM" and the color red. You can add a time and a timespan (14:20PM + 30 minutes) or two timespans (2 hours+30 minutes). But you cannot add two times.
To make this even clearer, consider what would happen if you could add two times: 14.20 + 00:30 (EST) = 23.20 + 09:30 (UTC)
Try this (although 0:30pm doesn't make sense):
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new StringTime("14:20 pm").Add(new StringTime("0:30 pm")));
Console.WriteLine(new StringTime("15:00 pm").Add(new StringTime("0:30 pm")));
Console.WriteLine(new StringTime("5:00am").Add(new StringTime("12:00pm")));
}
}
class StringTime
{
public int Hours { get; set; }
public int Minutes { get; set; }
public bool IsAfternoon { get; set; }
public StringTime(string timeString)
{
IsAfternoon = timeString.Contains("pm");
timeString = timeString.Replace("pm", "").Replace("am", "").Trim();
Hours = int.Parse(timeString.Split(':')[0]);
Minutes = int.Parse(timeString.Split(':')[1]);
}
public TimeSpan ToTimeSpan()
{
if (IsAfternoon)
{
if (Hours < 12)
{
Hours += 12;
}
}
return new TimeSpan(Hours, Minutes, 00);
}
public TimeSpan Add(StringTime time2)
{
return this.ToTimeSpan().Add(time2.ToTimeSpan());
}
}
Output (the value before the dot are days):
1.02:50:00
1.03:30:00
17:00:00