[Gambas-user] Format function changes date value

Tobias Boege taboege at gmail.com
Sat May 19 20:04:01 CEST 2018


Reposting my answer as well:

On Sat, 19 May 2018, George wrote:
> >T Lee Davidson <t.lee.davidson at gmail.com>
> >
> >CDate uses UTC and, without the time information in the string, it would store midnight. Format uses local time.
> >
> >So, anyone in a time zone behind UTC will get the previous day printed. Try this format string:
> >zTestResult = Format(CDate(zTestDate), "mm/dd/yy hh:nn ddd")
> >
> >Does the difference in hours match your timezone offset?
>
> That is definitely part of the issue.  My local time is GMT-04, and here's
> what I get when specifying the time in my test:
>
> Test date: 5/4/2018 03:59:00 Formatted: 05/03/18 Thu
> Test date: 5/4/2018 04:00:00 Formatted: 05/04/18 Fri
>
> However, if I look at time in the results, the difference isn't exactly the
> offset:
> Test date: 5/4/2018 03:59:00 Formatted: 05/03/18 23:05:00  Difference:
> 4:54:00
> Test date: 5/4/2018 04:00:00 Formatted: 05/04/18 00:05:00  Difference:
> 3:55:00
> Test date: 5/4/2018 00:00:00 Formatted: 05/03/18 20:05:00  Difference:
> 3:55:00
>
> The offset isn't an even number of hours. What's also odd is that this was
> never a problem before about a week ago.  This code is many years old, and
> the problem suddenly began occurring with compiled code.

This has been discussed multiple times recently, the last time was [1].
So let me elaborate on T Lee's answer a bit. The official statement is
that the previous behaviour was a bug which was unfortunately not
discovered sooner. As of Gambas 3.11, you should remember that CStr()
and CDate(), being low-level conversions, assume UTC, i.e. they convert
the date "literally" (without any offset) to a date and a time integer,
which is the internal representation of a Date in Gambas.

The higher-level Str(), Val(), Format() and Date() functions take the
current locale into account. Mixing CDate() with Format() is almost always
a bug, as one honours the local timezone and the other doesn't. CDate()
produces a Date object which is 05/04/18 00:00 UTC but when you format
it using Format$(), you get a string representing the same point in time
relative to your current timezone. I'm in GMT+0200 these days so I get:

  Test date: 5/4/2018 Formatted: 05/04/18 02:00 Fri

Removing the "C" from the invocation of CDate(), you chain locale-aware
functions only and get the desired result:

  Test date: 5/4/2018 Formatted: 05/04/18 00:00 Fri

That five minute offset you mention is indeed weird, though, and I have
no explanation for that.

Regards,
Tobi

[1] https://lists.gambas-basic.org/pipermail/user/2018-May/064153.html

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk


More information about the User mailing list