SULFIKAR A N
SULFIKAR A N

Reputation: 446

String to date conversion in c# as yyyy/mm/dd

I would like convert string content to date format as yyyy/MM/dd HH:mm:ss tt

string date = "2014-11-20 3:21:00 PM";
DateTime date_=System.DateTime.Now;

var result = DateTime.TryParseExact(date, "yyyy-MM-dd HH:mm:ss tt", 
                                    System.Globalization.CultureInfo.InvariantCulture, 
                                    System.Globalization.DateTimeStyles.None,
                                    out date_);

But it returns result doesn't match requirement also TryParse function return false. If time zone is not defined, it will return expected result.

Upvotes: 0

Views: 304

Answers (2)

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

Reputation: 98868

HH specifier is for 24 hour clock which is 00 to 23.

You need to use h specifier instead which represents 1 to 12 in 12 hour clock.

Also you don't need to initialize your out parameter value. Definition will be enough like;

string date = "2014-11-20 3:21:00 PM";
DateTime date_;

var result = DateTime.TryParseExact(date, "yyyy-MM-dd h:mm:ss tt",
                                    CultureInfo.InvariantCulture, 
                                    DateTimeStyles.None, out date_);

Upvotes: 5

ITGenius
ITGenius

Reputation: 139

The DateTime data type format is always MM/dd/yyyy hh:mm:ss tt (i.e. Date = {11/20/2014 12:00:00 AM}), If you want to display the value you can change the format by using ToString extention method

Upvotes: -1

Related Questions