14

I have a string like this: 250920111414

I want to create a DateTime object from that string. As of now, I use substring and do it like this:

string date = 250920111414;

int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
...
DateTime dt = new DateTime(year, month, day ...);

Is it possible to use string format, to do the same, without substring?

3
  • Even if it were, I don't think you'd gain anything - this looks like an entirely reasonable and readable approach. Commented Sep 28, 2011 at 9:08
  • 2
    @JeremyMcGee I dont find it that readable actually, i'd prefer Jons approach Commented Sep 28, 2011 at 9:10
  • It's readable for me, but were several people on the project. Commented Sep 28, 2011 at 9:21

3 Answers 3

26

Absolutely. Guessing the format from your string, you can use ParseExact

string format = "ddMMyyyyHHmm";

DateTime dt = DateTime.ParseExact(value, format, CultureInfo.InvariantCulture);

or TryParseExact:

DateTime dt;
bool success = DateTime.TryParseExact(value, format, 
                     CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);

The latter call will simply return false on parse failure, instead of throwing an exception - if you may have bad data which shouldn't cause the overall task to fail (e.g. it's user input, and you just want to prompt them) then this is a better call to use.

EDIT: For more details about the format string details, see "Custom Date and Time Format Strings" in MSDN.

Sign up to request clarification or add additional context in comments.

9 Comments

Do you really remember all those simple but useful solutions by heart or you have a big big big dictionary near your hand? :)
@Praetor12: For basics like DateTime.ParseExact I remember the method names, but sometimes get the parameters wrong - as I did here, first time :)
Jon Skeet is simply awesome! Sometimes I feel like having a +1000 button as well.
@Jon Skeet I told not about methods names, but about format strings. In C# there are so many "formats". May be there is a total list of them. Msdn has only sparse examples in different articles :(
Sometimes stackoverflow gives me that warm & cozy feeling. Like when I need to find info on reversing a custom DateTime.ToString() and I know that Jon Skeet will have answered it. And he did...
|
4

You could use:

DateTime dt = DateTime.ParseExact(
                  date, 
                  "ddMMyyyyHHmm",
                  CultureInfo.InvariantCulture);

Comments

0
string iDate = "05/05/2005";
DateTime oDate = Convert.ToDateTime(iDate);
DateTime oDate = DateTime.ParseExact(iString, "yyyy-MM-dd HH:mm tt",null);


DateTime Formats

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.