2

I receive DateTime in this format => yyyyMMddHHmmss e.g. 20160214204032

Due to its somewhat unique format, I can't just use Convert.ToDateTime -- I tried, it didn't work.

It's easy enough to create a helper method that would parse the components of this date e.g

var year = myString.Substring(0,4);

but I'm concerned that this may have poor performance.

Can anyone think of a better way to convert a string in this format to DateTime?

Sam
  • 26,817
  • 58
  • 206
  • 383
  • 6
    http://stackoverflow.com/questions/919244/converting-a-string-to-datetime – Jules Feb 15 '16 at 03:59
  • 2
    You can use `DateTime.ParseExact` with format parameter as `yyyyMMddHHmmss`. And use `DateTime.Year` to retrieve it. – choz Feb 15 '16 at 04:00

2 Answers2

4

You cannot set format in Convert.ToDateTime. So, use ParseExact instead.

DateTime.ParseExact("20160214204032", "yyyyMMddHHmmss",
                                       System.Globalization.CultureInfo.InvariantCulture)
CharithJ
  • 46,289
  • 20
  • 116
  • 131
1

Due to its somewhat unique format, I can't just use Convert.ToDateTime -- I tried, it didn't work.

It fails because Convert.ToDateTime tries to convert from your system Date Time Format and throws exception if it can't.

using String Functions is also bad to convert to DateTime so you can do

DateTime dt = DateTime.ParseExact("20160214204032", 
                                  "yyyyMMddHHmmss",
                                  System.Globalization.CultureInfo.InvariantCulture)
René Vogt
  • 43,056
  • 14
  • 77
  • 99
Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208