Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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?

like image 291
user3763216 Avatar asked Feb 01 '15 14:02

user3763216


2 Answers

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);
like image 152
Cyral Avatar answered Nov 08 '22 21:11

Cyral


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;
like image 21
Giorgi Nakeuri Avatar answered Nov 08 '22 19:11

Giorgi Nakeuri