How to combine two strings (date and time) to a si

2019-02-21 14:10发布

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?

9条回答
够拽才男人
2楼-- · 2019-02-21 14:23

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

查看更多
相关推荐>>
3楼-- · 2019-02-21 14:24

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}

查看更多
地球回转人心会变
4楼-- · 2019-02-21 14:25

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

查看更多
戒情不戒烟
5楼-- · 2019-02-21 14:25

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);
查看更多
仙女界的扛把子
6楼-- · 2019-02-21 14:40

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"));
查看更多
不美不萌又怎样
7楼-- · 2019-02-21 14:41

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'

查看更多
登录 后发表回答