apeksha
apeksha

Reputation:

How do I add times in C#?

How do I add times in C#? For example:

Time = "14:20 pm" +  "00:30 pm"

Upvotes: 1

Views: 30998

Answers (5)

Colin Pickard
Colin Pickard

Reputation: 46633

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

Upvotes: 21

weiqure
weiqure

Reputation: 3235

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

Upvotes: 2

MSalters
MSalters

Reputation: 179779

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)

Upvotes: 1

Kirschstein
Kirschstein

Reputation: 14868

 TimeSpan t1 = new TimeSpan(14, 20,0);
 TimeSpan t2 = new TimeSpan(0,30,0);
 Console.Out.WriteLine(t1 + t2);

Upvotes: 4

James
James

Reputation: 82096

You would want to convert both times into a TimeSpan objects.

This will give you explicit access to the Hours/Minutes values of each time and you can add them together.

See TimeSpan from MSDN.

Upvotes: 4

Related Questions