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?

2
  • 6
    stackoverflow.com/questions/919244/… Commented Feb 15, 2016 at 3:59
  • 2
    You can use DateTime.ParseExact with format parameter as yyyyMMddHHmmss. And use DateTime.Year to retrieve it. Commented Feb 15, 2016 at 4:00

2 Answers 2

4

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

DateTime.ParseExact("20160214204032", "yyyyMMddHHmmss",
                                       System.Globalization.CultureInfo.InvariantCulture)
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

This should be a comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.