Convert time string to DateTime

792 Views Asked by At

If I have, for example, a string that contains 12:20pm or 4:34am and want to create a DateTime Object with that string?

Essentially, I have a date picker and next to it a jquery time picker and so I want to combine those two to get a combined DateTime object that has both the user selected date as well as the user selected time.

6

There are 6 best solutions below

2
On BEST ANSWER

Try this:

    string date = "2015-06-10";
    string time = " 12:20pm";
    DateTime combinedResult = DateTime.Parse(date + time);
    Console.WriteLine(combinedResult.ToString());

The DateTime.Parse method converts string object to datetime object https://msdn.microsoft.com/en-us/library/1k1skd40%28v=vs.110%29.aspx

0
On

You can use DateTime.ParseExact() method with desired format string.

0
On

With DateTime.Parse() you can parse any string into a DateTime object. If the values of your two pickers have different formats, you can provide the combined format as a 2nd parameter to the Parse function.

0
On
    You can this is simple way to do it.

    string tm = "10:24PM";
    string dt = "6/10/2015";
    DateTime dt2 = Convert.ToDateTime(dt + " "+tm);
    Response.Write(dt2);
0
On

Try using the time span, something like below :

TimeSpan time = TimeSpan.ParseExact("23:59:59(Your string)", "HH:mm:ss", null);
0
On

You do not need to make a string to combine date and time. I don't know the jquery time picker, but if it provides a DateTime oject you can do

var combined = datePicker.Value.Add(timePicker.Value.TimeOfDay);