mherr
mherr

Reputation: 378

VB.NET - Unable to enforce two digit day and month when converting string to Date

I am having difficulty taking a string and converting it to a vb.net Date object, while enforcing two digit day and month. Please consider the following form example, using today's date. (02/01/2019)

    Dim myDate As Date = Date.Now

    Dim myDateString = String.Format("{0:D2}/{1:D2}/{2:D4}", myDate.Month, myDate.Day, myDate.Year)

    myDate = DateTime.ParseExact(myDateString, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None)

    Label1.Text = myDate 'This will show "2/1/2019"

    Label2.Text = myDateString 'This will show "02/01/2019"

This situation leaves Label1.Text as "2/1/2019", but Label2.Text as "02/01/2019". No matter what I have tried, it appears that the actual conversion from the correctly formatted String into a Date object will remove these zeros. Does anyone have any thoughts as to how I can enforce a "MM/dd/yyyy" format when converting to a Date object?

Thank you in advance,

Upvotes: 0

Views: 1959

Answers (1)

Steve
Steve

Reputation: 216313

You should consider that a DateTime variable has no format. It is just a number expressing the Ticks elapsed from the starting DateTime.MinValue (1/1/0001).
It has no memory that you have built it using a particular formatting parser.

So, when you assign a date to a string like you do in your

Label1.Text = myDate

then you are asking the ToString representation of that date. The output of this method without a formatting parameter is whatever your locale settings decide it to be. If you want to force the desidered output you need to tell the date's ToString method in what format you want the output

Label1.Text = myDate.ToString("MM/dd/yyyy")

Upvotes: 5

Related Questions