O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generate a Culture-Invariant Date String

Problem

You want to convert a date or time into a formatted string that has the same representation, regardless of the globalization settings of the current computer.

Solution

Use the overloaded DateTime.ToString method that accepts an IFormatProvider instance, and supply the DateTimeFormatInfo.InvariantInfo object.

Discussion

In some cases, you want dates to be formatted identically regardless of the settings on the computer running the code. This might be the case if the string value of the date is being inserted into a legacy database. Using a custom format string will offer some protection (if you are careful to only use numeric date information), but to be completely reassured you should specify the culture ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required