Project

General

Profile

12161a_3_now.patch

Stefanel Pezamosca, 11/13/2026 02:42 AM

Download (30.1 KB)

View differences:

new/src/com/goldencode/p2j/util/date.java
245 245
** 110 RNC 20260521          Instantiate the date primitive type as unknown if a null value is provided.
246 246
** 111 AS  20260831          Dropped 'synchronized' from initialValue(): the container is a static singleton,
247 247
**                           so the monitor serialized every context in the JVM while protecting no state.
248
** 112 SP  20261110          TODAY, TIME and TIMEZONE read the clock once and use TimeZone.getOffset().
249
**                           TIME follows SESSION:TIMEZONE.
248 250
*/
249 251

  
250 252
/*
......
1560 1562
   }
1561 1563
   
1562 1564
   /**
1563
    * Get the default timezone for the date received as parameter. In case of null,
1564
    * the default JVM timezone's "offset" (raw + dst) converted from milliseconds to 
1565
    * minutes.
1566
    * 
1565
    * Get the default timezone offset, in minutes, for the date received as parameter: the
1566
    * SESSION:TIMEZONE offset if set, otherwise the default JVM timezone's raw offset plus its DST
1567
    * savings when the date is in daylight time. In case of null, the offset at the current instant
1568
    * (see {@link #currentOffset(long)}).
1569
    *
1567 1570
    * @param    d
1568
    *           The date for which we want to calculate the timezone's offset.
1569
    * 
1570
    * @return   The default timezone.
1571
    *           The date for which we want to calculate the timezone's offset, or {@code null} for now.
1572
    *
1573
    * @return   The default timezone offset in minutes.
1571 1574
    */
1572 1575
   public static int getDefaultOffset(Date d)
1573 1576
   {
1577
      if (d == null)
1578
      {
1579
         return currentOffset(System.currentTimeMillis());
1580
      }
1581

  
1574 1582
      integer tzAttr = work.obtain().timezoneOffset; // date.getSessionTimeZone()
1575 1583
      int     offset = 0;
1576
      
1584

  
1577 1585
      if (tzAttr.isUnknown())
1578 1586
      {
1579 1587
         // get the raw offset in millis and convert it to minutes
1580 1588
         TimeZone defTz = TimeZone.getDefault(); 
1581 1589
         // it seems that in Progress the timezone also contains the DST
1582 1590
         offset = defTz.getRawOffset();
1583
         if (d == null && defTz.inDaylightTime(new Date()) || 
1584
             d != null && defTz.inDaylightTime(d))
1591
         if (defTz.inDaylightTime(d))
1585 1592
         {
1586 1593
            offset += defTz.getDSTSavings();
1587 1594
         }
......
1594 1601
      
1595 1602
      return offset;
1596 1603
   }
1597
   
1604

  
1605
   /**
1606
    * Get the default timezone offset at an instant: the SESSION:TIMEZONE offset if set, otherwise
1607
    * the offset of the default JVM timezone at that instant, DST included.
1608
    *
1609
    * @param    utc
1610
    *           The instant, in milliseconds since the Java epoch.
1611
    *
1612
    * @return   The offset in minutes from UTC.
1613
    */
1614
   static int currentOffset(long utc)
1615
   {
1616
      integer tzAttr = work.obtain().timezoneOffset;
1617

  
1618
      // getOffset() rather than raw offset plus DST savings: the two differ in zones such as
1619
      // Africa/Casablanca, whose DST data does not fit a fixed DST amount
1620
      return tzAttr.isUnknown() ? TimeZone.getDefault().getOffset(utc) / (1000 * 60) : tzAttr.intValue();
1621
   }
1622

  
1623
   /**
1624
    * Get the wall clock of the default timezone (see {@link #currentOffset(long)}) at an instant.
1625
    *
1626
    * @param    utc
1627
    *           The instant, in milliseconds since the Java epoch.
1628
    *
1629
    * @return   The local date and time, in milliseconds since the Java epoch.
1630
    */
1631
   static long localMillis(long utc)
1632
   {
1633
      return utc + currentOffset(utc) * 60_000L;
1634
   }
1635

  
1598 1636
   /**
1599 1637
    * Get the default timezone as specified in the SESSION:TIMEZONE offset or
1600 1638
    * if not specified there, the default JVM timezone.
......
1610 1648
    * Obtains the effective default timezone offset in minutes from UTC for
1611 1649
    * this user's context. This will get the default timezone as specified in
1612 1650
    * the SESSION:TIMEZONE offset or if not specified there, the default JVM
1613
    * timezone's "raw offset" (in milliseconds) converted to minutes.  This is
1651
    * timezone's offset at the current instant, DST included (see {@link #currentOffset(long)}).  This is
1614 1652
    * a form of the TIMEZONE built-in function.
1615 1653
    *
1616 1654
    * @return   The effective default timezone offset in minutes from UTC.
......
2045 2083
   }
2046 2084

  
2047 2085
   /**
2048
    * Returns the number of seconds since midnight in the current JVM timezone.
2086
    * Returns the number of seconds since midnight in the SESSION:TIMEZONE, or in the JVM timezone
2087
    * when that is not set. This is the TIME built-in function.
2049 2088
    *
2050 2089
    * @return   The number of seconds since midnight.
2051 2090
    */
2052 2091
   public static int64 secondsSinceMidnight()
2053 2092
   {
2054
      // this represents the current time in the default JVM timezone
2055
      return secondsSinceMidnight(new GregorianCalendar());
2093
      return int64.of(Math.floorMod(localMillis(System.currentTimeMillis()), MILLIS_PER_DAY) / 1000);
2056 2094
   }
2057 2095
   
2058 2096
   /**
......
2105 2143
   }
2106 2144
   
2107 2145
   /**
2108
    * Creates an instance that represents today's date using the local system clock time.
2146
    * Creates an instance that represents today's date in the SESSION:TIMEZONE, or in the JVM timezone when
2147
    * that is not set.
2109 2148
    * @return today's date
2110 2149
    */
2111 2150
   public static date today()
......
4272 4311
   }
4273 4312
      
4274 4313
   /**
4275
    * Calculates the current date using the local system clock time.
4314
    * Calculates the current date in the SESSION:TIMEZONE, or in the JVM timezone when that is not set.
4276 4315
    *
4277 4316
    * @return   The current date as a julian day number.
4278 4317
    */
4279 4318
   private static long _today()
4280 4319
   {
4281
      return millisToJulianDay(dateToLocalMillis(null, date.getDefaultTimeZone()));
4320
      return Math.floorDiv(localMillis(System.currentTimeMillis()), MILLIS_PER_DAY) + JULIAN_EPOCH_OFFSET;
4282 4321
   }
4283 4322
   
4284 4323
   /**
new/src/com/goldencode/p2j/util/datetime.java
66 66
** 035 AL2 20250530 Added getIndependentFromContext.
67 67
** 036 VVT 20260107 Adapt to date class changes, add missing @Override annotations, remove unused imports
68 68
**                  and obsolete instantiateUnknownDatetime() method. See #9846.
69
** 037 SP  20261110 now() and millisecondsSinceMidnight() read the clock once, without calendars.
69 70
*/
70 71

  
71 72
/*
......
860 861
   /**
861 862
    * Creates an instance that represents current date and time using the default timezone.
862 863
    * This is the equivalent of the NOW built-in function.
864
    *
865
    * @return   The current date and time in the SESSION:TIMEZONE, or in the JVM timezone when that is
866
    *           not set.
863 867
    */
864 868
   public static datetime now()
865 869
   {
866
      TimeZone sessionTz = date.getDefaultTimeZone();
867
      GregorianCalendar now = getZoneCalendar(sessionTz);
868
      
869
      return new datetime(date.today(), datetime.millisSinceMidnight(now));
870
      return nowAt(System.currentTimeMillis());
870 871
   }
871 872
   
872 873
   /**
......
1447 1448
    */
1448 1449
   public static integer millisecondsSinceMidnight()
1449 1450
   {
1450
      return new integer(datetime.now().time);
1451
      return new integer(Math.floorMod(date.localMillis(System.currentTimeMillis()), date.MILLIS_PER_DAY));
1451 1452
   }
1452 1453

  
1453 1454
   /**
......
2951 2952
   }
2952 2953
   
2953 2954
   /**
2954
    * Extract the portion of the calendar representing the number of
2955
    * milliseconds since midnight.
2955
    * Creates an instance with the date and time of the SESSION:TIMEZONE, or of the JVM timezone when
2956
    * that is not set, at the given instant.
2956 2957
    *
2957
    * @param    cal
2958
    *           The calendar instance to query.
2958
    * @param    utc
2959
    *           The instant, in milliseconds since the Java epoch.
2959 2960
    *
2960
    * @return   The milliseconds since midnight.
2961
    * @return   The date and time at that instant.
2961 2962
    */
2962
   private static int millisSinceMidnight(Calendar cal)
2963
   static datetime nowAt(long utc)
2963 2964
   {
2964
      int hour   = cal.get(Calendar.HOUR_OF_DAY);
2965
      int mins   = cal.get(Calendar.MINUTE);
2966
      int secs   = cal.get(Calendar.SECOND);
2967
      int millis = cal.get(Calendar.MILLISECOND);
2968
      
2969
      return (((((hour * 60) + mins) * 60) + secs) * 1000) + millis;
2965
      long     local = date.localMillis(utc);
2966
      datetime ret   = new datetime();
2967

  
2968
      ret.setDayNumber(Math.floorDiv(local, date.MILLIS_PER_DAY) + date.JULIAN_EPOCH_OFFSET);
2969
      ret.setTime(Math.floorMod(local, date.MILLIS_PER_DAY));
2970

  
2971
      return ret;
2970 2972
   }
2971 2973
   
2972 2974
   /**
new/src/com/goldencode/p2j/util/datetimetz.java
2 2
** Module   : datetimetz.java
3 3
** Abstract : Progress 4GL compatible datetime-tz object
4 4
**
5
** Copyright (c) 2013-2025, Golden Code Development Corporation.
5
** Copyright (c) 2013-2026, Golden Code Development Corporation.
6 6
**
7 7
** -#- -I- --Date-- ------------------------------------Description------------------------------------------
8 8
** 001 GES 20130128 Initial commit with basic functionality.
......
69 69
** 033 ICP 20250129 Used int64.of to leverage caches instances.
70 70
** 034 AL2 20250530 Added getIndependentFromContext.
71 71
** 035 AS  20260421 Offset the BC epoch years by 1 to account for 0 based years in OffsetDateTime.
72
** 036 SP  20261110 now() reads the clock once and sets its value directly.
72 73
*/
73 74

  
74 75
/*
......
1211 1212
    */
1212 1213
   public static datetimetz now()
1213 1214
   {
1214
      // NOW uses the SESSION:TIME-ZONE if set or local-time otherwise
1215
      integer sessionOffset = date.getTimeZone();
1216
      int sessOffset = sessionOffset.isUnknown() ?
1217
            datetimetz.getDefaultTimezoneOffset(null) :
1218
            sessionOffset.intValue();
1219
      
1220
      return new datetimetz(datetime.now(), sessOffset);
1215
      return nowAt(System.currentTimeMillis());
1221 1216
   }
1222 1217
   
1223 1218
   /**
......
2427 2422
   }
2428 2423
   
2429 2424
   /**
2425
    * Creates an instance for the given instant, with the SESSION:TIMEZONE offset, or the JVM timezone's
2426
    * offset at that instant when that is not set.
2427
    *
2428
    * @param    utc
2429
    *           The instant, in milliseconds since the Java epoch.
2430
    *
2431
    * @return   The datetime-tz value of that instant.
2432
    */
2433
   static datetimetz nowAt(long utc)
2434
   {
2435
      // the wall clock comes from the same offset that is stored, so they always agree
2436
      int        offset = date.currentOffset(utc);
2437
      long       local  = utc + offset * 60_000L;
2438
      datetimetz ret    = new datetimetz();
2439

  
2440
      ret.setDayNumber(Math.floorDiv(local, date.MILLIS_PER_DAY) + date.JULIAN_EPOCH_OFFSET);
2441
      ret.setTime(Math.floorMod(local, date.MILLIS_PER_DAY));
2442
      ret.setTimeZoneOffset(offset);
2443

  
2444
      return ret;
2445
   }
2446

  
2447
   /**
2430 2448
    * Private utility method that returns a Calendar value as string in ISO format 
2431 2449
    * (yyyy-MM-dd hh:mm:ss.ttt).
2432 2450
    * 
new/test/com/goldencode/p2j/util/DatetimetzNowTest.java
1
/*
2
** Module   : DatetimetzNowTest.java
3
** Abstract : Tests for NOW and the clock functions that share its code.
4
**
5
** Copyright (c) 2026, Golden Code Development Corporation.
6
**
7
** -#- -I- --Date-- ---------------------------------Description---------------------------------
8
** 001 SP  20261110 Created initial version.
9
*/
10

  
11
/*
12
** This program is free software: you can redistribute it and/or modify
13
** it under the terms of the GNU Affero General Public License as
14
** published by the Free Software Foundation, either version 3 of the
15
** License, or (at your option) any later version.
16
**
17
** This program is distributed in the hope that it will be useful,
18
** but WITHOUT ANY WARRANTY; without even the implied warranty of
19
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
** GNU Affero General Public License for more details.
21
**
22
** You may find a copy of the GNU Affero GPL version 3 at the following
23
** location: https://www.gnu.org/licenses/agpl-3.0.en.html
24
**
25
** Additional terms under GNU Affero GPL version 3 section 7:
26
**
27
**   Under Section 7 of the GNU Affero GPL version 3, the following additional
28
**   terms apply to the works covered under the License.  These additional terms
29
**   are non-permissive additional terms allowed under Section 7 of the GNU
30
**   Affero GPL version 3 and may not be removed by you.
31
**
32
**   0. Attribution Requirement.
33
**
34
**     You must preserve all legal notices or author attributions in the covered
35
**     work or Appropriate Legal Notices displayed by works containing the covered
36
**     work.  You may not remove from the covered work any author or developer
37
**     credit already included within the covered work.
38
**
39
**   1. No License To Use Trademarks.
40
**
41
**     This license does not grant any license or rights to use the trademarks
42
**     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
43
**     of Golden Code Development Corporation. You are not authorized to use the
44
**     name Golden Code, FWD, or the names of any author or contributor, for
45
**     publicity purposes without written authorization.
46
**
47
**   2. No Misrepresentation of Affiliation.
48
**
49
**     You may not represent yourself as Golden Code Development Corporation or FWD.
50
**
51
**     You may not represent yourself for publicity purposes as associated with
52
**     Golden Code Development Corporation, FWD, or any author or contributor to
53
**     the covered work, without written authorization.
54
**
55
**   3. No Misrepresentation of Source or Origin.
56
**
57
**     You may not represent the covered work as solely your work.  All modified
58
**     versions of the covered work must be marked in a reasonable way to make it
59
**     clear that the modified work is not originating from Golden Code Development
60
**     Corporation or FWD.  All modified versions must contain the notices of
61
**     attribution required in this license.
62
*/
63

  
64
package com.goldencode.p2j.util;
65

  
66
import static org.junit.jupiter.api.Assertions.*;
67

  
68
import java.util.*;
69

  
70
import org.junit.jupiter.api.*;
71

  
72
/**
73
 * Tests for {@link datetimetz#now()} and the clock functions that share its code: {@link datetime#now()}
74
 * ({@code INIT NOW} of a DATETIME, NOW compared with a DATETIME),
75
 * {@link datetime#millisecondsSinceMidnight()} (MTIME), {@link date#today()},
76
 * {@link date#secondsSinceMidnight()} (TIME) and {@link date#getDefaultTimeZoneOffset()} (TIMEZONE).
77
 * <p>
78
 * The expected values follow the JDK's rules for the JVM default time zone. OpenEdge uses the machine's
79
 * zone the same way; the {@code SESSION:TIMEZONE} cases follow the OpenEdge results of {@code dtz_now.p}.
80
 */
81
public class DatetimetzNowTest
82
{
83
   /** Milliseconds per minute. */
84
   private static final long MS_PER_MINUTE = 60_000L;
85

  
86
   /** Clock slack allowed between the bounds a test reads and the value under test. */
87
   private static final long SLACK_MS = 50L;
88

  
89
   /**
90
    * JVM default zones the tests run under: whole-hour, half-hour, 45-minute and +/-14:00 offsets, zones
91
    * with DST, and the zones whose DST data makes raw offset plus DST savings differ from the real offset.
92
    */
93
   private static final String[] ZONES =
94
   {
95
      "UTC", "Europe/Bucharest", "America/New_York", "America/St_Johns", "Asia/Kolkata", "Asia/Kathmandu",
96
      "Australia/Lord_Howe", "Pacific/Chatham", "Pacific/Kiritimati", "Pacific/Pago_Pago",
97
      "America/Vancouver", "Africa/Casablanca", "Africa/El_Aaiun", "Africa/Windhoek"
98
   };
99

  
100
   /** {@code SESSION:TIMEZONE} values checked against OpenEdge by {@code dtz_now.p}. */
101
   private static final int[] SESSION_OFFSETS = { 60, -300, 330, 345, 765, 840, -840, -570, -60 };
102

  
103
   /** The default time zone at the start of each test. */
104
   private TimeZone savedZone;
105

  
106
   /**
107
    * Saves the default time zone and clears {@code SESSION:TIMEZONE}.
108
    */
109
   @BeforeEach
110
   public void saveZone()
111
   {
112
      savedZone = TimeZone.getDefault();
113
      date.setTimeZone(new integer());
114
   }
115

  
116
   /**
117
    * Restores the default time zone and clears {@code SESSION:TIMEZONE}.
118
    */
119
   @AfterEach
120
   public void restoreZone()
121
   {
122
      TimeZone.setDefault(savedZone);
123
      date.setTimeZone(new integer());
124
   }
125

  
126
   /**
127
    * With {@code SESSION:TIMEZONE} unset, NOW is the current instant and carries the JVM zone's offset at
128
    * that instant.
129
    */
130
   @Test
131
   public void nowIsCurrentInstantWithJvmZoneOffset()
132
   {
133
      List<String> failures = new ArrayList<>();
134
      for (String id : ZONES)
135
      {
136
         TimeZone zone = TimeZone.getTimeZone(id);
137
         TimeZone.setDefault(zone);
138

  
139
         long before = System.currentTimeMillis();
140
         datetimetz now = datetimetz.now();
141
         long after = System.currentTimeMillis();
142

  
143
         long instant = instantOf(now);
144
         int expectedOffset = zone.getOffset(instant) / (int) MS_PER_MINUTE;
145
         if (instant < before - SLACK_MS || instant > after + SLACK_MS || now.getOffset() != expectedOffset)
146
         {
147
            failures.add(id + ": instant off by " + (instant - before) + " ms, offset " + now.getOffset() +
148
                         " instead of " + expectedOffset);
149
         }
150
      }
151
      assertEquals(Collections.emptyList(), failures);
152
   }
153

  
154
   /**
155
    * With {@code SESSION:TIMEZONE} unset, TIMEZONE is the offset NOW carries.
156
    */
157
   @Test
158
   public void timezoneIsOffsetOfNow()
159
   {
160
      List<String> failures = new ArrayList<>();
161
      for (String id : ZONES)
162
      {
163
         TimeZone.setDefault(TimeZone.getTimeZone(id));
164
         int timezone = date.getDefaultTimeZoneOffset().intValue();
165
         int nowOffset = datetimetz.now().getOffset();
166
         if (timezone != nowOffset)
167
         {
168
            failures.add(id + ": TIMEZONE " + timezone + ", TIMEZONE(NOW) " + nowOffset);
169
         }
170
      }
171
      assertEquals(Collections.emptyList(), failures);
172
   }
173

  
174
   /**
175
    * With {@code SESSION:TIMEZONE} unset, the DATETIME form of NOW (MTIME, {@code INIT NOW}) and TODAY give
176
    * the JVM zone's wall clock.
177
    */
178
   @Test
179
   public void datetimeNowAndTodayAreJvmZoneWallClock()
180
   {
181
      List<String> failures = new ArrayList<>();
182
      for (String id : ZONES)
183
      {
184
         TimeZone zone = TimeZone.getTimeZone(id);
185
         TimeZone.setDefault(zone);
186

  
187
         long before = wallClock(zone, System.currentTimeMillis());
188
         datetime now = datetime.now();
189
         date today = date.today();
190
         long after = wallClock(zone, System.currentTimeMillis());
191

  
192
         long wall = localMillisOf(now);
193
         if (wall < before - SLACK_MS || wall > after + SLACK_MS)
194
         {
195
            failures.add(id + ": datetime.now() off by " + (wall - before) + " ms");
196
         }
197
         if (today.longValue() != dayNumber(before) && today.longValue() != dayNumber(after))
198
         {
199
            failures.add(id + ": TODAY " + today.longValue() + " instead of " + dayNumber(before));
200
         }
201
      }
202
      assertEquals(Collections.emptyList(), failures);
203
   }
204

  
205
   /**
206
    * With {@code SESSION:TIMEZONE} unset, TIME and MTIME are the seconds and milliseconds of the JVM zone's
207
    * wall clock.
208
    */
209
   @Test
210
   public void timeAndMtimeAreJvmZoneWallClock()
211
   {
212
      List<String> failures = new ArrayList<>();
213
      for (String id : ZONES)
214
      {
215
         TimeZone zone = TimeZone.getTimeZone(id);
216
         TimeZone.setDefault(zone);
217

  
218
         long before = Math.floorMod(wallClock(zone, System.currentTimeMillis()), date.MILLIS_PER_DAY);
219
         long mtime = datetime.millisecondsSinceMidnight().longValue();
220
         long time = date.secondsSinceMidnight().longValue();
221
         long after = Math.floorMod(wallClock(zone, System.currentTimeMillis()), date.MILLIS_PER_DAY);
222

  
223
         if (todDistance(mtime, before) > SLACK_MS && todDistance(mtime, after) > SLACK_MS)
224
         {
225
            failures.add(id + ": MTIME off by " + (mtime - before) + " ms");
226
         }
227
         if (todDistance(time * 1000, before) > 1000 + SLACK_MS &&
228
             todDistance(time * 1000, after) > 1000 + SLACK_MS)
229
         {
230
            failures.add(id + ": TIME off by " + (time * 1000 - before) + " ms");
231
         }
232
      }
233
      assertEquals(Collections.emptyList(), failures);
234
   }
235

  
236
   /**
237
    * With {@code SESSION:TIMEZONE} set, NOW is the current instant, carries the session offset, and
238
    * TIMEZONE returns it. OpenEdge does this for every offset {@code dtz_now.p} tries.
239
    */
240
   @Test
241
   public void nowCarriesSessionOffset()
242
   {
243
      List<String> failures = new ArrayList<>();
244
      for (String id : new String[] { "Europe/Bucharest", "Africa/Casablanca" })
245
      {
246
         TimeZone.setDefault(TimeZone.getTimeZone(id));
247
         for (int offset : SESSION_OFFSETS)
248
         {
249
            date.setTimeZone(new integer(offset));
250

  
251
            long before = System.currentTimeMillis();
252
            datetimetz now = datetimetz.now();
253
            long after = System.currentTimeMillis();
254

  
255
            long instant = instantOf(now);
256
            int timezone = date.getDefaultTimeZoneOffset().intValue();
257
            if (instant < before - SLACK_MS || instant > after + SLACK_MS ||
258
                now.getOffset() != offset ||
259
                timezone != offset)
260
            {
261
               failures.add(id + " session " + offset + ": instant off by " + (instant - before) +
262
                            " ms, TIMEZONE(NOW) " + now.getOffset() + ", TIMEZONE " + timezone);
263
            }
264
         }
265
      }
266
      assertEquals(Collections.emptyList(), failures);
267
   }
268

  
269
   /**
270
    * With {@code SESSION:TIMEZONE} set, the DATETIME form of NOW (MTIME, {@code INIT NOW}, NOW compared with
271
    * a DATETIME), MTIME and TODAY follow the session zone's wall clock, as in OpenEdge.
272
    */
273
   @Test
274
   public void datetimeNowMtimeAndTodayFollowSessionZone()
275
   {
276
      List<String> failures = new ArrayList<>();
277
      TimeZone.setDefault(TimeZone.getTimeZone("Europe/Bucharest"));
278
      for (int offset : SESSION_OFFSETS)
279
      {
280
         date.setTimeZone(new integer(offset));
281

  
282
         long before = System.currentTimeMillis() + offset * MS_PER_MINUTE;
283
         datetime now = datetime.now();
284
         long mtime = datetime.millisecondsSinceMidnight().longValue();
285
         date today = date.today();
286
         long after = System.currentTimeMillis() + offset * MS_PER_MINUTE;
287

  
288
         long wall = localMillisOf(now);
289
         if (wall < before - SLACK_MS || wall > after + SLACK_MS)
290
         {
291
            failures.add("session " + offset + ": datetime.now() off by " + (wall - before) + " ms");
292
         }
293
         if (todDistance(mtime, Math.floorMod(before, date.MILLIS_PER_DAY)) > SLACK_MS &&
294
             todDistance(mtime, Math.floorMod(after, date.MILLIS_PER_DAY)) > SLACK_MS)
295
         {
296
            failures.add("session " + offset + ": MTIME off by " +
297
                         (mtime - Math.floorMod(before, date.MILLIS_PER_DAY)) + " ms");
298
         }
299
         if (today.longValue() != dayNumber(before) && today.longValue() != dayNumber(after))
300
         {
301
            failures.add("session " + offset + ": TODAY " + today.longValue() + " instead of " +
302
                         dayNumber(before));
303
         }
304
      }
305
      assertEquals(Collections.emptyList(), failures);
306
   }
307

  
308
   /**
309
    * With {@code SESSION:TIMEZONE} set, TIME follows the session zone's wall clock, as in OpenEdge.
310
    */
311
   @Test
312
   public void timeFollowsSessionZone()
313
   {
314
      List<String> failures = new ArrayList<>();
315
      TimeZone.setDefault(TimeZone.getTimeZone("Europe/Bucharest"));
316
      for (int offset : SESSION_OFFSETS)
317
      {
318
         date.setTimeZone(new integer(offset));
319

  
320
         long shift = offset * MS_PER_MINUTE;
321
         long before = Math.floorMod(System.currentTimeMillis() + shift, date.MILLIS_PER_DAY);
322
         long time = date.secondsSinceMidnight().longValue();
323
         long after = Math.floorMod(System.currentTimeMillis() + shift, date.MILLIS_PER_DAY);
324

  
325
         if (todDistance(time * 1000, before) > 1000 + SLACK_MS &&
326
             todDistance(time * 1000, after) > 1000 + SLACK_MS)
327
         {
328
            failures.add("session " + offset + ": TIME off by " + (time * 1000 - before) + " ms");
329
         }
330
      }
331
      assertEquals(Collections.emptyList(), failures);
332
   }
333

  
334
   /**
335
    * With {@code SESSION:TIMEZONE} set, assigning NOW to a DATETIME keeps the instant and gives the wall
336
    * clock of the machine zone, not of the session zone, as in OpenEdge.
337
    */
338
   @Test
339
   public void datetimeAssignedFromNowUsesMachineZone()
340
   {
341
      List<String> failures = new ArrayList<>();
342
      TimeZone zone = TimeZone.getTimeZone("Europe/Bucharest");
343
      TimeZone.setDefault(zone);
344
      for (int offset : SESSION_OFFSETS)
345
      {
346
         date.setTimeZone(new integer(offset));
347

  
348
         long before = wallClock(zone, System.currentTimeMillis());
349
         datetime assigned = new datetime();
350
         assigned.assign(datetimetz.now());
351
         long after = wallClock(zone, System.currentTimeMillis());
352

  
353
         long wall = localMillisOf(assigned);
354
         if (wall < before - SLACK_MS || wall > after + SLACK_MS)
355
         {
356
            failures.add("session " + offset + ": DATETIME = NOW off by " + (wall - before) + " ms");
357
         }
358
      }
359
      assertEquals(Collections.emptyList(), failures);
360
   }
361

  
362
   /**
363
    * NOW for a given instant takes its offset, day and time from that instant: across the DST changes of
364
    * 2026 (Europe/Bucharest whole hour, Australia/Lord_Howe 30 minutes), across midnight (2025-11-10), and
365
    * with SESSION:TIMEZONE set to -840 and 345.
366
    */
367
   @Test
368
   public void nowAtUsesOneInstant()
369
   {
370
      TimeZone.setDefault(TimeZone.getTimeZone("Europe/Bucharest"));
371
      assertEquals("2461130/10799999/120", parts(datetimetz.nowAt(1774745999999L)));
372
      assertEquals("2461130/14400000/180", parts(datetimetz.nowAt(1774746000000L)));
373
      assertEquals("2461340/14399999/180", parts(datetimetz.nowAt(1792889999999L)));
374
      assertEquals("2461340/10800000/120", parts(datetimetz.nowAt(1792890000000L)));
375
      assertEquals("2460991/86399999/120", parts(datetimetz.nowAt(1762811999999L)));
376
      assertEquals("2460992/0/120",        parts(datetimetz.nowAt(1762812000000L)));
377
      assertEquals("2461340/10800000",     parts(datetime.nowAt(1792890000000L)));
378

  
379
      TimeZone.setDefault(TimeZone.getTimeZone("Australia/Lord_Howe"));
380
      assertEquals("2461137/7199999/660", parts(datetimetz.nowAt(1775314799999L)));
381
      assertEquals("2461137/5400000/630", parts(datetimetz.nowAt(1775314800000L)));
382
      assertEquals("2461319/7199999/630", parts(datetimetz.nowAt(1791041399999L)));
383
      assertEquals("2461319/9000000/660", parts(datetimetz.nowAt(1791041400000L)));
384

  
385
      date.setTimeZone(new integer(-840));
386
      assertEquals("2460991/28800000/-840", parts(datetimetz.nowAt(1762812000000L)));
387
      assertEquals("2460991/28800000",      parts(datetime.nowAt(1762812000000L)));
388
      date.setTimeZone(new integer(345));
389
      assertEquals("2460992/13500000/345",  parts(datetimetz.nowAt(1762812000000L)));
390
   }
391

  
392
   /**
393
    * NOW for a fixed instant (2025-11-10T22:00:00Z) carries the real offset of zones whose raw offset plus
394
    * DST savings differs from it, and the wall clock of that offset; TIMEZONE agrees with it.
395
    */
396
   @Test
397
   public void nowAtUsesRealOffsetInIrregularDstZones()
398
   {
399
      long utc = 1762812000000L;
400
      TimeZone.setDefault(TimeZone.getTimeZone("Africa/Casablanca"));
401
      assertEquals("2460991/82800000/60", parts(datetimetz.nowAt(utc)));
402
      assertEquals("2460991/82800000",    parts(datetime.nowAt(utc)));
403
      assertEquals(60,                    date.currentOffset(utc));
404

  
405
      TimeZone.setDefault(TimeZone.getTimeZone("Africa/El_Aaiun"));
406
      assertEquals("2460991/82800000/60", parts(datetimetz.nowAt(utc)));
407

  
408
      TimeZone.setDefault(TimeZone.getTimeZone("Africa/Windhoek"));
409
      assertEquals("2460992/0/120", parts(datetimetz.nowAt(utc)));
410
      assertEquals("2460992/0",     parts(datetime.nowAt(utc)));
411
      assertEquals(120,             date.currentOffset(utc));
412
   }
413

  
414
   /**
415
    * Gets the day number, time and, for a datetime-tz, offset of a value.
416
    *
417
    * @param    value
418
    *           The value.
419
    *
420
    * @return   {@code day/time} or {@code day/time/offset}.
421
    */
422
   private static String parts(datetime value)
423
   {
424
      String text = value.longValue() + "/" + value.getTime();
425
      return value instanceof datetimetz ? text + "/" + ((datetimetz) value).getOffset() : text;
426
   }
427

  
428
   /**
429
    * Gets the instant a datetime-tz value stands for.
430
    *
431
    * @param    value
432
    *           The value.
433
    *
434
    * @return   Milliseconds since the Java epoch, UTC.
435
    */
436
   private static long instantOf(datetimetz value)
437
   {
438
      return localMillisOf(value) - value.getOffset() * MS_PER_MINUTE;
439
   }
440

  
441
   /**
442
    * Gets the wall clock a datetime value holds, as milliseconds since the Java epoch in its own zone.
443
    *
444
    * @param    value
445
    *           The value.
446
    *
447
    * @return   The day number and time of day of the value, in milliseconds.
448
    */
449
   private static long localMillisOf(datetime value)
450
   {
451
      return (value.longValue() - date.JULIAN_EPOCH_OFFSET) * date.MILLIS_PER_DAY + value.getTime();
452
   }
453

  
454
   /**
455
    * Gets the wall clock of a zone at an instant, by the JDK's zone rules.
456
    *
457
    * @param    zone
458
    *           The zone.
459
    * @param    utc
460
    *           The instant, in milliseconds since the Java epoch.
461
    *
462
    * @return   The wall clock, in milliseconds since the Java epoch in that zone.
463
    */
464
   private static long wallClock(TimeZone zone, long utc)
465
   {
466
      return utc + zone.getOffset(utc);
467
   }
468

  
469
   /**
470
    * Gets the 4GL day number of a wall clock.
471
    *
472
    * @param    local
473
    *           The wall clock, in milliseconds since the Java epoch.
474
    *
475
    * @return   The day number.
476
    */
477
   private static long dayNumber(long local)
478
   {
479
      return Math.floorDiv(local, date.MILLIS_PER_DAY) + date.JULIAN_EPOCH_OFFSET;
480
   }
481

  
482
   /**
483
    * Gets the distance between two times of day, across midnight.
484
    *
485
    * @param    a
486
    *           Milliseconds of the day.
487
    * @param    b
488
    *           Milliseconds of the day.
489
    *
490
    * @return   The distance in milliseconds, at most half a day.
491
    */
492
   private static long todDistance(long a, long b)
493
   {
494
      long d = Math.floorMod(a - b, date.MILLIS_PER_DAY);
495
      return Math.min(d, date.MILLIS_PER_DAY - d);
496
   }
497
}