-2

I'm trying to add a string that represents a time to a c# datetime object but I'm getting a exception that says 'invalid format'

details.UTCEventDate.Add(TimeSpan.Parse(details.UTCEventTime));

where 'details.UTCEventTime' is something like "4:45AM"

chuckd
  • 13,460
  • 29
  • 152
  • 331

2 Answers2

1

AM and PM values are not easily parsed with TimeSpan.Parse becuase TimeSpan technically represents a length of a time interval, not a time of day itself.

You can however use DateTime.Parse method to parse this value and then retrieve the time part using the TimeOfDay property as a TimeSpan:

details.UTCEventDate.Add( DateTime.Parse( details.UTCEventTime ).TimeOfDay );

If you wanted to specify the format even more precisely using ParseExact, you could use the h:mmtt format string where tt represents AM and PM part.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
0

TimeSpan.Parse does not like "AM/PM" in the string.

What you can do is

details.UTCEventDate.Add(DateTime.Parse(details.UTCEventTime).TimeOfDay)
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Shinva
  • 1,899
  • 18
  • 25