How to add time in datetime in C#?


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#?


Asked by:- neena
1
: 343 At:- 7/18/2022 11:23:09 AM
C# add time to datime







1 Answers
profileImage Answered by:- vikas_jk

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.

0
At:- 7/18/2022 11:29:45 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly