I have two strings:
string one = \"13/02/09\";
string two = \"2:35:10 PM\";
I want to combine these two together and convert to a Dat
Your issue is with your hour specifier; you want h
(The hour, using a 12-hour clock from 1 to 12), not HH
(The hour, using a 24-hour clock from 00 to 23).
I had different format and the above answer did not work:
string one = "2019-02-06";
string two = "18:30";
The solution for this format is:
DateTime newDateTime = Convert.ToDateTime(one).Add(TimeSpan.Parse(two));
The result will be: newDateTime{06-02-2019 18:30:00}
Try using a culture info which matches the DateTime
format for your string values:
DateTime dt = Convert.ToDateTime(one + " " + two,
CultureInfo.GetCultureInfo("ro-RO"));
or modify the input string so that the hour has 2 digits:
string one = "13/02/09";
string two = "02:35:10 PM";
DateTime dt1 = DateTime.ParseExact(one + " " + two,
"dd/MM/yy HH:mm:ss tt",
CultureInfo.InvariantCulture);
The following code will do what you want. I used the UK culture to take care of the d/m/y structure of your date:
string string1 = "13/2/09";
string string2 = "2:35:10 PM";
DateTime combined = DateTime.Parse(string1 + ' ' + string2, new CultureInfo("UK"));
use DateTime.Parse () to parse the date and the time separately. Then add the time component of the second one to the first one, like this
var date = DateTime.Parse (one);
var time = DateTime.Parse (two);
var result = date + time - time.Date;
Convert.ToDateTime
uses DateTime.ParseExact
with your current thread's culture, so you can make things a bit clearer by simply doing:
string date = "13/02/09";
string time = "2:35:10 PM";
DateTime dateTime = DateTime.Parse(date +" "+ time, new CultureInfo("en-GB"));
Console.WriteLine (dateTime);
That gives the result 13/02/2009 14:35:10
, and forces the parse to use the en-GB date time formats. If your Windows installation is en-GB anyway, you don't need the CultureInfo(..)
argument.