Musikero31
Musikero31

Reputation: 3153

Add the current Date.Now to a TimeSpan?

This is similar to this link: "Add the current time to a DateTime?" but mine is quite different.

I would like to know how to add your timespan (example: 10:00AM) to your Date.Now (ex. 7/3/2013)? I've tried the DateTime.Now.Add(timeSpan) but it does not work.

Any suggestions?

Upvotes: 0

Views: 2463

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can use the + operator:

TimeSpan ts = TimeSpan.FromHours(10);
DateTime result = DateTime.Now + ts;

However, DateTime.Add should work also. I assume that your "TimeSpan" is a string instead.

Since your timespan contains the AM/PM designator you can parse it to DateTime instead and add the TimeOfDay-TimeSpan to DateTime.Now:

DateTime time = DateTime.ParseExact("10:00AM", "hh:mmtt", CultureInfo.InvariantCulture);
DateTime result = DateTime.Now + time.TimeOfDay;

Demo

Edit: If you want to add the TimeSpan to midnight use DateTime.Today instead of DateTime.Now.

Upvotes: 1

keyboardP
keyboardP

Reputation: 69372

DateTime is immutable so your existing variable won't change.

var myDateTime = DateTime.Now.Add(timeSpan);

Upvotes: 3

Related Questions