0

I have a formatted datetime string and I want to convert it back to DateTime but when I parse or convert that string to DateTime it throws exceptio that string is not a valid dateTime.

Here is how DateTime string is created

string temp = dt.Year.ToString("D4") + 
              dt.Month.ToString("D2") + 
              dt.Day.ToString("D2") + 
              dt.Hour.ToString("D2") + 
              dt.Minute.ToString("D2") + 
              dt.Second.ToString("D2");

and here is how i am parsing it back to DateTime

 DateTime dtchk = DateTime.Parse(temp);
thomas
  • 1,399
  • 1
  • 17
  • 32
AddyProg
  • 2,960
  • 13
  • 59
  • 110

1 Answers1

3

Yes it is but this is happening in a different module.

I don't even understand what is that mean. I think you just need;

DateTime dtchk = dt;

Nothing more. But anyway.. I try to explain;

Since "D" format specifier generates string representation with leading zeros if your string length is less than precision specifier, your temp will be the combination of these wider formats of months, day, hour etc..

And DateTime.Parse parses your string successfully if this string is a standard date and time format of your CurrentCulture. In your case, it is not.

You need to parse your string with ParseExact to specify your formats exactly.

DateTime dtchk = DateTime.ParseExact(temp, "yyyyMMddHHmmss", null);
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364