user3763216
user3763216

Reputation: 489

Split string (birthday) to get day, month, year

In my database, date is stored as dd/mm/yyyy. When I retrieve it I want to split the date in string day, string month and string year respectively. How should I go about doing it? "/" will be the delimiter is that right?

Upvotes: 7

Views: 27907

Answers (2)

Cyral
Cyral

Reputation: 14153

You need can use DateTime.ParseExact with format "dd/MM/yyyy": (Where myString is the birthday from the database.)

string myString = "01/02/2015"; // From Database
DateTime birthday = DateTime.ParseExact(myString, "dd/MM/yyyy", CultureInfo.InvariantCulture);

int year = birthday.Year;
int month = birthday.Month;
int day = birthday.Day;

You can then use the DateTime object to get the year, month, day, etc.

Using string.Split is an option too, but storing as a DateTime allows you to use many handy methods/properties it contains, but you can do it using string.Split as so:

string[] birthday = myString.Split('/');
int year, month, day;

int.TryParse(birthday[0], out day);
int.TryParse(birthday[1], out month);
int.TryParse(birthday[2], out year);

Upvotes: 9

Giorgi Nakeuri
Giorgi Nakeuri

Reputation: 35780

If you get birthDate from database as string, you can use split function to split that string into array like:

   string birthDate = "2015/02/01";
   var split = birthDate.Split('/');

If you get birthDate from database as datetime, you can extract date parts from it like:

    DateTime birthDate = DateTime.Now.Date;

    var year = birthDate.Year;
    var month = birthDate.Month;
    var day = birthDate.Day;

Upvotes: 7

Related Questions