Govind Malviya
Govind Malviya

Reputation: 13743

DateTime conversion exception

This is code

String date = "1980/1/1"; 
DateTime dateTime = DateTime.ParseExact(date, "yyyy/MM/DD", null);
// I have also tried 
// DateTime dateTime = DateTime.ParseExact(date, "yyyy/MM/DD", CultureInfo.InvariantCulture);

and this is Exception

String was not recognized as a valid DateTime.

Update

Getting same error using following code

 DateTime dateTime = DateTime.ParseExact(date, "yyyy/M/D", null);

Upvotes: 0

Views: 457

Answers (3)

Habib Zare
Habib Zare

Reputation: 1204

try this (tested)

String date = "1980/1/1";
DateTime dateTime = DateTime.ParseExact(date, "yyyy'/'M'/'d",null);

the character slash is between single qoutation.

Upvotes: 1

Habib
Habib

Reputation: 223237

use single M and Single d

DateTime dateTime = DateTime.ParseExact(date, "yyyy/M/d", null);

Single M will take care for month 01, 1 to 12, similarly Single d will take care of day from 1 to 31, including 01 to 09

You may see: Custom Date and Time Format Strings - MSDN

Upvotes: 2

John Woo
John Woo

Reputation: 263703

use only yyyy/M/D. it threw an exception because it is expecting yyyy/01/01 two digits for month and day.

DateTime dateTime = DateTime.ParseExact(date, "yyyy/M/d", null);

Upvotes: 1

Related Questions