MRebai
MRebai

Reputation: 5474

Convert string to Datetime dd/MM/yyyy hh:mm:ss tt

How can I convert this 7/3/2015 12:40:02 PM to DateTime with format "dd/MM/yyyy hh:mm:ss tt" I have done like this:

BreackEndTime = DateTime.ParseExact(configViewModel.EndPause, "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

But I always get

String was not recognized as a valid DateTime.

enter code here

Upvotes: 4

Views: 62123

Answers (4)

Diego Slinger
Diego Slinger

Reputation: 149

This is the code that worked well in my case:

        Console.WriteLine("deal with regex datetime: ");
        string input = "11/24 5:41:00 AM";
        DateTime newDate;
        CultureInfo enUS = new CultureInfo("en-US");
        try
        {
            newDate = DateTime.ParseExact(input, "M/d h:mm:ss tt", CultureInfo.InvariantCulture);
            Console.WriteLine("parse result: " + newDate);
        }
        catch (Exception err)
        {
            Console.WriteLine("error parsing input string. date format is wrong or string chaged " + err);
        }

Upvotes: 1

user7995637
user7995637

Reputation: 1

FORMAT(CM.TransactionDate,'hh:mm:ss tt')

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460078

Since months and days can have a single digit use

BreackEndTime = DateTime.ParseExact(configViewModel.EndPause, "d/M/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

The "M" Custom Format Specifier (exemplary, d works similar)

The "M" custom format specifier represents the month as a number from 1 through 12 (or from 1 through 13 for calendars that have 13 months). A single-digit month is formatted without a leading zero.

Update

Since the hour can also have a single digit you have to use:

DateTime.ParseExact("7/3/2015 1:52:16 PM", "d/M/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);` 

... so "d/M/yyyy h:mm:ss tt" instead of "d/M/yyyy hh:mm:ss tt". Note that the same applies to the minutes and seconds, if they also can have single digits use "d/M/yyyy h:m:s tt". I hope you got the point now.

Upvotes: 21

Soner Gönül
Soner Gönül

Reputation: 98750

If your 7/3/2015 12:40:02 PM is string, you need to use single digit format specifiers as M specifier and d specifier like;

BreackEndTime = DateTime.ParseExact(configViewModel.EndPause,
                                    "M/d/yyyy hh:mm:ss tt", 
                                    CultureInfo.InvariantCulture);

Upvotes: 2

Related Questions