Kam
Kam

Reputation: 109

TimePicker and DateTime object

I am trying to implement a check in my app that user must select time greater than current time along with i am taking their difference. I am taking time from user through a time picker and comparing with a datetime object. I am facing a problem doing this.

        DateTime  obj = DateTime.Now.ToLocalTime();
        DateTime obj2 = Convert.ToDateTime(tp.Time);
        //Here tp.time is the time from timepicker.
        //But the exception isthrown that it cannot convert timespan to datetime. 

        TimeSpan ts = obj - obj2;

Upvotes: 0

Views: 296

Answers (2)

Michael Samteladze
Michael Samteladze

Reputation: 1330

Try this

var t1 = tp.Time;
var t2 = DateTime.Now.TimeOfDay;
TimeSpan ts = t2 - t1;

Upvotes: 0

meneses.pt
meneses.pt

Reputation: 2616

Time from the TimePicker control is a TimeSpan.

To achieve what you are trying to do you can do the following:

DateTime  obj = DateTime.Now.ToLocalTime();
DateTime obj2 = DateTime.Today.Add(tp.Time);

TimeSpan ts = obj - obj2;

Upvotes: 1

Related Questions