Question

I set the date variable

Dim myDate as Date
myDate = #5/15/2013#

Does this work always at runtime, no matter what is the system locale settings?

Était-ce utile?

La solution

According to the MSDN documentation:

You must enclose a Date literal within number signs (# #). You must specify the date value in the format M/d/yyyy, for example #5/31/1993#. This requirement is independent of your locale and your computer's date and time format settings.

The reason for this restriction is that the meaning of your code should never change depending on the locale in which your application is running. Suppose you hard-code a Date literal of #3/4/1998# and intend it to mean March 4, 1998. In a locale that uses mm/dd/yyyy, 3/4/1998 compiles as you intend. But suppose you deploy your application in many countries. In a locale that uses dd/mm/yyyy, your hard-coded literal would compile to April 3, 1998. In a locale that uses yyyy/mm/dd, the literal would be invalid (April 1998, 0003) and cause a compiler error.

So, the answer to your question is YES, it will always work at runtime, and NO, you do not need to change this for the locale settings of the computer.

Do keep in mind that date literals are somewhat frowned upon. They are supported in VB.Net as a backwards-familiarity thing from VB6. They don't even exist in other .Net languages like C#. If you have to hard-code a specific date, you are much better off using DateTime with separate parameters, such as:

Dim myDate as DateTime
myDate = new DateTime(2013,5,15)

Also note that Date is just a VB.Net alias to System.DateTime, again there for backwards familiarity from VB6. It doesn't matter which you use, they mean the same thing.

Autres conseils

No, that does not work in a country such as Canada where the standard is dd/MM/yyyy. The best way to globalize your application would be to use DateTime.ParseExact and/or DateTime.TryParseExact

        Dim tempdate As DateTime

        tempdate = DateTime.ParseExact("05/20/2013", "MM/dd/yyyy", Globalization.CultureInfo.InvariantCulture)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top