0

I'm getting FormatException with this piece of code

string yyyy = OPENING_DATE.Substring(0, 4);
string mm = OPENING_DATE.Substring(4, 2);
string dd = OPENING_DATE.Substring(6, 2);
ncbaccount.Date_Opened = string.Format("{1}/{2}/{3}",dd,mm,yyyy);

PROBLEM: OPENING_DATE is like '20140317'

SOLUTION: I want a string like '17/03/2014'

Thanks

2
  • 12
    Format placeholders begin at {0}, not {1}. Commented Mar 17, 2014 at 10:24
  • 5
    Change "{1}/{2}/{3}" to "{0}/{1}/{2}". Commented Mar 17, 2014 at 10:25

3 Answers 3

11

Instead of splitting your date string, then formatting it and parsing, you can use DateTime.ParseExact and provide format of date string:

DateTime date = 
     DateTime.ParseExact(OPENING_DATE, "yyyyMMdd", CultureInfo.InvariantCulture);
Sign up to request clarification or add additional context in comments.

3 Comments

@oliverdejohnson This will then let you hold the date in a proper DateTime type and go on to convert back to a string with better formatting options available.
also use .ToString() for above, as you want the date in string format
ok many thanks...I like the idea.in converting back to the required string format i added this below your code: string.Format("{0:dd/mm/yyyy}",date);
6

Replace {1}/{2}/{3} with {0}/{1}/{2} as it begins at 0.

Ex:

string yyyy = OPENING_DATE.Substring(0, 4);
        string mm = OPENING_DATE.Substring(4, 2);
        string dd = OPENING_DATE.Substring(6, 2);
        ncbaccount.Date_Opened = string.Format("{0}/{1}/{2}", dd, mm, yyyy);

1 Comment

chosen as answer cos it answered the original question. Implemented Sergey's solution though cos its kinda neater
0

Only change this line

string.Format("{0}/{1}/{2}", dd, mm, yyyy);

More over you should be using DateTime Functions to parse date and times.

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.