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

后端 未结 9 1090
刺人心
刺人心 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:50

    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).

    0 讨论(0)
  • 2021-01-17 11:50

    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}

    0 讨论(0)
  • 2021-01-17 11:53

    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);
    
    0 讨论(0)
  • 2021-01-17 11:53

    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"));
    
    0 讨论(0)
  • 2021-01-17 11:53

    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;
    
    0 讨论(0)
  • 2021-01-17 11:54

    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.

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