[All]
Using VarToStr on a variant containing a date does not honour the SysUtils.ShortDateFormat, it continues to use the OS settings.
Abstract: Using VarToStr on a variant containing a date does not honour the SysUtils.ShortDateFormat, it continues to use the OS settings.
- Product Name: Delphi
- Product Version: 2006
- Product Component: Compiler
- Platform/OS Version: Win32
Description:
Using VarToStr on a variant containing a date does not honour the SysUtils.ShortDateFormat, it continues to use the OS settings.
Answer/Solution:
The reason for this is that deep in the bowels of the Variant unit, VarToStr calls an OS API function which is hard coded to use the user?s, default locale. Working around the issue is fairly simple as by extracting the raw date data from the variant.
var
� DateVariant : Variant;
begin
�� Application.UpdateFormatSettings := False;
�� SysUtils.ShortDateFormat := 'dd#MM#yyyy'; //uses a strange shortdateformat string
�� ShowMessage(DateToStr(Date));�
�� //Image this variant is being pulled out from a database
�� DateVariant := Date;
�� ShowMessage(VarToStr(DateVariant)); //this will show the date using the OS date settings
�� ShowMessage(DateToStr(TVarData(DateVariant).VDate)); //using some creative casting the issue can be resolved.
end;