Jericho
Jericho

Reputation: 81

How to input a formatted date in a text box?

I'm confuse about how to make an input of formatted date time and currency. I want user to input the DoB as dd/mm/yyyy but when I'm using DateTime data type in Visual Studio it only get yyyy/mm/dd format.

Here's my code: This is DoB and property from another class employee.cs

 class employee
    {
        private DateTime myBOD;
public DateTime BOD
        {
            get
            {
                return myBOD;
            }
            set
            {
                myBOD = value;
            }
        }
}

This is the main form1.cs

vemployee.BOD = Convert.ToDateTime(bod.Text);
var today = DateTime.Today;
age.Text = Convert.ToString(today.Year-vemployee.BOD.Year);

Upvotes: 0

Views: 5290

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Well, DateTime is a struct it doesn't have any format but properties like Year, Month, Day etc. use DateTime.ParseExact when you want to obtain DateTime from string:

 vemployee.BOD = DateTime.ParseExact(
   bod.Text, 
  "dd'/'MM'/'yyyy", // Please, note that "mm" stands for minutes, not months
   CultureInfo.InvariantCulture);

And .ToString(format) when you want to represent DateTime as a string

 DateTime today = DateTime.Today;

 bod.Text = today.ToString("dd'/'MM'/'yyyy", CultureInfo.InvariantCulture);

Upvotes: 2

Related Questions