Hello, If I have a time string "4:49 pm" or timespan value and I would like to add it in a datetime value, how can i do it in C#?
ok, you can simply convert string to datetime in C# and then add datetime ticks into another datetime value, as shown below
var eventCloseTime = "4:39 PM"; //time in string
DateTime date = DateTime.Now.Date; // get only date
//convert time into datetime
DateTime dateTime = DateTime.ParseExact(eventCloseTime, "h:mm tt", System.Globalization.CultureInfo.InvariantCulture);
//add time into datetime
var updatedDatetime = date.AddTicks(dateTime.TimeOfDay.Ticks);
Output:
07/18/2022 16:39:00
Fiddle link: https://dotnetfiddle.net/Hi3QH5
Thanks, hope it helps.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly