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 DateTime
.
I tried the following but it doesn't work:
DateTime dt = Convert.ToDateTime(one + " " + two);
DateTime dt1 = DateTime.ParseExact(one + " " + two, "dd/MM/yy HH:mm:ss tt", CultureInfo.InvariantCulture);
What can I do to make this work?
Try like this;
Here is a DEMO.
HH using a 24-hour clock from
00
to23
. For example;1:45:30 AM -> 01
and1:45:30 PM -> 13
h using a 12-hour clock from 1 to 12. For example;
1:45:30 AM -> 1
and1:45:30 PM -> 1
Check out for more information Custom Date and Time Format Strings
I had different format and the above answer did not work:
The solution for this format is:
The result will be: newDateTime{06-02-2019 18:30:00}
Your issue is with your hour specifier; you want
h
(The hour, using a 12-hour clock from 1 to 12), notHH
(The hour, using a 24-hour clock from 00 to 23).Try using a culture info which matches the
DateTime
format for your string values:or modify the input string so that the hour has 2 digits:
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:
The problem is that the format string that you specify is not correct.
'HH' means a dwo-digit hour, but you have a single digit hour.
Use 'h' instead.
So the full format is 'dd/MM/yy h:mm:ss tt'