Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 352
user2082630 Avatar asked Feb 18 '13 09:02

user2082630


People also ask

How do I combine date and time in typescript?

getFullYear(); const mm = new Date(date). getMonth() + 1; const dd = new Date(date). getDate(); const completeDate = new Date(mm + dd + yy + time); console. log(yy); console.


2 Answers

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

like image 58
Soner Gönül Avatar answered Oct 12 '22 00:10

Soner Gönül


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}

like image 44
Divya Agrawal Avatar answered Oct 11 '22 23:10

Divya Agrawal