oJM86o
oJM86o

Reputation: 2118

take time and append to date to make datetime?

Say I have the following:

string fromTime = "8:00am";
string someDate = "06/01/2012";

I want to end up doing this:

DateTime dt = Convert.ToDateTime(someDate + someTime);

Basically I want to take a date and add the time to it with the result for the above to be

06/01/2012 8:00am

But have it stored in a datetime variable. Is this possible?

Upvotes: 2

Views: 143

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039348

You could use the DateTime.TryParseExact method which allows you to specify a format when parsing:

class Program
{
    static void Main()
    {
        string s = "06/01/2012 8:00am";
        string format = "dd/MM/yyyy h:mmtt";
        DateTime date;
        if (DateTime.TryParseExact(s, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
        {
            Console.WriteLine(date);
        }
    }
}

Upvotes: 6

Steven Doggart
Steven Doggart

Reputation: 43743

Try this:

DateTime dt = DateTime.ParseExact(someDate + " " + someTime, "MM/dd/yyyy h:mmtt", CultureInfo.InvariantCulture);

Upvotes: 1

Related Questions