Ashwini Agivale
Ashwini Agivale

Reputation: 145

How to find multiple substrings

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.

Upvotes: 1

Views: 809

Answers (5)

Landi
Landi

Reputation: 661

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.

Upvotes: 2

Maksim Vi.
Maksim Vi.

Reputation: 9225

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

Upvotes: 4

vijay
vijay

Reputation: 1353

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);
}

Upvotes: 0

Christoffer Lette
Christoffer Lette

Reputation: 14816

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.

Upvotes: 0

mck
mck

Reputation: 988

You can try this

string [] date = dateOfbirth.Split('-');
string year = date[0];
string month = date[1];
string day = date[2];

Upvotes: 5

Related Questions