Click here to Skip to main content
15,881,849 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
private void button1_Click(object sender, EventArgs e)
{
    TimeSpan a = new TimeSpan(12, 00, 00);
    TimeSpan b = new TimeSpan(13, 00, 00);

    TimeSpan r = b - a;
    TimeSpan rr = new TimeSpan(r.Ticks / 2);

    MessageBox.Show("Test\n " + rr);   ///this is type TimeSpan

    dateTimePicker.Value =Convert.ToDateTime(rr);   /// ERROR" Additional Information: An object of type 'System.TimeSpan' can not be converted to type 'System.IConvertible'. "
}


What I have tried:

dateTimePicker.Value =Convert.ToDateTime(rr);


and

c# - Convert DateTime to TimeSpan - Stack Overflow[^]


Try it on your IDE
Posted
Updated 29-Aug-17 3:30am
Comments
cvogt61457 29-Aug-17 9:12am    
Well, TimeSpan is a difference of 2 times. It isn't a time itself.
You need at DataTime to use as a reference time with the TimeSpan to create a time.
Rodrigo Alex Rodriguez 29-Aug-17 9:15am    
Do you have an example?

You can't convert a Timespan to a DateTime: that doesn't work because it's not a logical action. Think about it: If I ask you to meet me at "plus 6 hours 30 minutes" what does that mean? Nothing - unless it's understood that there is a starting point for it to be relative to. In terms of normal conversation, "I'll meet you in thirty minutes" is fine - it's understood by all parties that that means "thirty minutes from now" but without that understanding we will all miss the appointment.

In computing terms you can include the current time very easily:
TimeSpan a = new TimeSpan(12, 00, 00);
DateTime dt = DateTime.Now + a;
But you can't expect a TimeSpan to convert directly.
 
Share this answer
 
Comments
Herman<T>.Instance 13-Sep-21 9:59am    
Better store the Ticks (long/Int64)
You can not convert a time span to a datetime.

You might add the span to a specific datetime (e.g. the current time).

If the span is always positive and less than 24 hours, you can use the DateTimePicker with the time only (see How to: Display Time with the DateTimePicker Control | Microsoft Docs[^]) by getting and setting the time members accordingly.

Otherwise you can use an UpDown control, create your own or search the web.

An example might be the Time Picker[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900