How can you customize only the dateformat of CultureInfos?

56 Views Asked by At

I want to create a IFormatProvider such that number formatting works like it does in CultureInfo.InvariantCulture but date formatting works customized to a short date.

Such that AnyStringDoubleDate.ToString(CultureInfo.InvariantCulture) results in a long dateformat for dates, which I don't want, but all other formats are fine already.

Is there a way to change this behavior for dates? I can only use String.ToString().

1

There are 1 best solutions below

2
Olivier Jacot-Descombes On

Of what type is AnyStringDoubleDate? You cannot format a string. Formatting is involved when converting a non-string value to a string. Therefore, you must start with a System.DateTime (having the alias Date in VB). Then you can specify a format by using this overload of DateTime.ToString:

Public Function ToString (format As String, provider As IFormatProvider) As 
String

Then you can write:

Dim s  As String
Dim dt As Date

dt = ...
s = dt.ToString("d", DateTimeFormatInfo.InvariantInfo)  ' ==> 08/17/2000
' OR
s = dt.ToString("g", DateTimeFormatInfo.InvariantInfo)  ' ==> 08/17/2000 16:32

Or use any other Standard date and time format string or a Custom date and time format string.