How to combine two strings (date and time) to a single DateTime

后端 未结 9 1091
刺人心
刺人心 2021-01-17 11:34

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

相关标签:
9条回答
  • 2021-01-17 11:56

    Use string two = "02:35:10 PM"; instead of string two = "2:35:10 PM"; and also hh instead of HH due to AM/PM format.

    Below is the code:

    string one = "13/02/09";
    string two = "02:35:10 PM";
    
    DateTime dateTime = DateTime.ParseExact(one + " " + two, "dd/MM/yy hh:mm:ss tt", CultureInfo.InvariantCulture);
    
    0 讨论(0)
  • 2021-01-17 12:06

    Try like this;

    string one = "13/02/09";
    string two = "2:35:10 PM";
    
    DateTime dt = Convert.ToDateTime(one + " " + two);
    DateTime dt1 = DateTime.ParseExact(one + " " + two, "dd/MM/yy h:mm:ss tt", CultureInfo.InvariantCulture);
    
    Console.WriteLine(dt1);
    

    Here is a DEMO.

    HH using a 24-hour clock from 00 to 23. For example; 1:45:30 AM -> 01 and 1:45:30 PM -> 13

    h using a 12-hour clock from 1 to 12. For example; 1:45:30 AM -> 1 and 1:45:30 PM -> 1

    Check out for more information Custom Date and Time Format Strings

    0 讨论(0)
  • 2021-01-17 12:07

    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'

    0 讨论(0)
提交回复
热议问题