Offset
Offset

Reputation: 53

Add minutes to Current Specified time

I want to add 5 minutes to specified time here is my code below.

string startTime = "1:00 AM";
string endTime = "0:05 AM";

TimeSpan duration = DateTime.Parse(endTime).Add(DateTime.Parse(startTime));

I keep getting error how can I had 5 minutes on to 1:00 AM to become 1:05 AM?

Upvotes: 0

Views: 6324

Answers (3)

MetaColon
MetaColon

Reputation: 2923

You can't add a time, you can only add a span. However, you can get the span of a DateTime through the TimeOfDay property:

string startTime = "1:00 AM";
string endTime = "0:05 AM";

DateTime duration = DateTime.Parse(startTime).Add(DateTime.Parse(endTime).TimeOfDay);

However, directly using a timeSpan is more recommendable (you have to remove the AM, as it is a span and not a DateTime):

string startTime = "1:00 AM";
string endTime = "0:05";

DateTime duration = DateTime.Parse(startTime).Add(TimeSpan.Parse(endTime));

If you know that you'll never going to add something else than minutes, I'd do something like this:

string startTime = "1:00 AM";
int minutes = 5;

DateTime duration = DateTime.Parse(startTime).AddMinutes(minutes);

You can learn more about DateTime here.

Upvotes: 2

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You are passing the whole DateTime object, while you need to pass only the Minute property after parsing the endTime string and then use the AddMinutes method on the parsed DateTime object of startTime for this :

DateTime updateTime = DateTime.Parse(startTime).AddMinutes(DateTime.Parse(endTime).Minute);

It will return the DateTime object adding 5 minutes to the original DateTime object i.e. 1:00 AM and the reuslt would be 1:05 AM

See the working DEMO Fiddle here

Upvotes: 1

Artak
Artak

Reputation: 2887

The Add method has an overload which gets TimeSpan. Use it as follows:

DateTime dt = DateTime.UtcNow; // this should be your value actually
DateTime newTime = dt.Add(TimeSpan.FromMinutes(5);

System.DateTime.Add method documentation on MSDN

Upvotes: 1

Related Questions