1

I have stored date of birth var char format:

Example: 1989-8-15

I want to find out sub string from it i.e I want separate year, month and date. I have tried it with following code:

string dateOfbirth = (string)(DataBinder.Eval(e.Item.DataItem, "dob"));

int length = (dateOfbirth).Length;
int index1 = dateOfbirth.IndexOf('-');
int index2 = dateOfbirth.IndexOf('-', index1 + 1);
string year = dateOfbirth.Substring(0, index1);
string month = dateOfbirth.Substring(index+1, index2-1);
string day = dateOfbirth.Substring(index2, length);

I am getting an error. Please suggest a solution. Thanks in advance.

2
  • what does the error say? Commented Jun 26, 2013 at 9:54
  • 1
    Why don't you use something like the following to achieve this effect: string[] arrDateOfbirth = dateOfbirth.Split('-'); Then you can select a value by stepping through the array... Commented Jun 26, 2013 at 9:58

5 Answers 5

5

You can try this

string [] date = dateOfbirth.Split('-');
string year = date[0];
string month = date[1];
string day = date[2];
Sign up to request clarification or add additional context in comments.

Comments

4
DateTime dob = DateTime.ParseExact("1989-8-15","yyyy-M-dd",null);
Console.WriteLine(dob.Year);
Console.WriteLine(dob.Month);
Console.WriteLine(dob.Day);

Clean and easy.

UPD: changed Parse to ParseExact with a custom date format

1 Comment

Instead of .Parse you should use .TryParseExact to avoid exception due to different culure settings
2

I hope this will help:

string st= "1989-8-15"; / 
string st = (string)(DataBinder.Eval(e.Item.DataItem, "dob"));

string [] stArr = st.Split('-');

So, you now have an array with dob items.

Comments

0

To actually answer your question:

string dateOfbirth = "1989-8-15";

int length = (dateOfbirth).Length;
int index1 = dateOfbirth.IndexOf('-');
int index2 = dateOfbirth.IndexOf('-', index1 + 1);

string year = dateOfbirth.Substring(0, index1);
string month = dateOfbirth.Substring(index1 + 1, index2 - index1 - 1);
string day = dateOfbirth.Substring(index2 + 1, length - index2 - 1);

It's just a matter of providing the correct parameters to the Substring method.

Using dateOfBirth.Split('-') would probably be at better solution for your problem, though.

Comments

0

Use TryParseExact to avoid exception due to different culture settings

DateTime dateValue;
var dateString="1989-08-15";
if(DateTime.TryParseExact(dateString, "yyyy-MM-dd", CultureInfo.InvariantCulture,DateTimeStyles.None, out dateValue))
{
// parse successfull
Console.WriteLine(dateValue.Year);
Console.WriteLine(dateValue.Month);
Console.WriteLine(dateValue.Day);
}

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.