0

I've a GCalendar class that interact with Google Calendar API:

public class GEvent
{
    public DateTime StartDate { get; set; }
    public TimeSpan StartTime { get; set; }
    public DateTime EndDate { get; set; }
    public TimeSpan EndTime { get; set; }
}

how you can see there are two properties StartTime and EndTime that is both TimeSpan.

Now I've created an object that instantiates this class, like so:

Calendar.GEvent eventD = new Calendar.GEvent();

I take the value of the StartTime and EndTime from a custom control. This control however return a DateTime instead of a TimeSpan, so I need to convert the DateTime into TimeSpan. This is what I did:

eventD.StartTime = new TimeSpan((long)EventTimeStart.SelectedTime.Value);

where EventTimeStart is the custom control. Now there is a problem the new TimeSpan waiting for a long, so I tried to implicit cast the control value into (long) but I get:

Cannot convert the type System.DateTime into 'Long'

I also tried with:

long startTime = EventTimeStart.SelectedTime.Value;

but is the same thing. How can I do for fix this?

enter image description here

Dillinger
  • 1,823
  • 4
  • 33
  • 78
  • `yourDateTime.TimeOfDay`. You cant `convert` DateTime into Timespan as TimeSpan is part of DateTime. Its like trying to convert a car into a wheel. – C4d Apr 30 '16 at 10:49
  • @C4ud3x I doens't have `TimeOfDay` on `EventTimeStart.` – Dillinger Apr 30 '16 at 10:52
  • Then, `EventTimeStart` isnt a DateTime!? – C4d Apr 30 '16 at 10:53
  • @C4ud3x ok I found the property was on `EventTimeStart.SelectedTime.Value.TimeOfDay` but the compiler tell me: `Cannot Convert System.TimeSpan to Long` – Dillinger Apr 30 '16 at 10:59
  • A TimeSpan is a time between two DateTime objects. DateTime in Net library starts at Jan 1, 1900. There are a few things I can't tell from your posting. 1) Does StartDate and EndDate contain hours and minutes or are they the Time at Midnight? Is StartTime and EndTime just the hours and minutes from Midnight or are they the time from Jan 1, 1900? – jdweng Apr 30 '16 at 11:32
  • Possible duplicate of [Convert DateTime to TimeSpan](http://stackoverflow.com/questions/17959440/convert-datetime-to-timespan) – Mostafiz Apr 30 '16 at 13:20

1 Answers1

2

Here it is:

TimeSpan startTime = EventTimeStart.SelectedTime.Value.TimeOfDay;

As TimeSpan is a part of DateTime, you cant convert. But you can pick it up with .TimeOfDay.

According the error in the comments: Dont try to store TimeSpan in long.
long time = something.TimeOfDay; wont work.

C4d
  • 3,183
  • 4
  • 29
  • 50