• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "ecmascript/js_date.h"
17 
18 #include <ctime>
19 #include <regex>
20 #include <sys/time.h>
21 
22 #include "ecmascript/date_parse.h"
23 #include "ecmascript/object_fast_operator-inl.h"
24 #include "ecmascript/platform/time.h"
25 
26 namespace panda::ecmascript {
27 using NumberHelper = base::NumberHelper;
28 static const std::array<CString, WEEKDAY> WEEK_DAY_NAME = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
29 static const std::array<CString, MOUTH_PER_YEAR> MONTH_NAME  = {
30     "Jan", "Feb", "Mar", "Apr", "May", "Jun",
31     "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
32 };
TransferTimeToDate(int64_t timeMs,std::array<int64_t,DATE_LENGTH> * date)33 void DateUtils::TransferTimeToDate(int64_t timeMs, std::array<int64_t, DATE_LENGTH> *date)
34 {
35     (*date)[HOUR] = Mod(timeMs, MS_PER_DAY);                                 // ms from hour, minutes, second, ms
36     (*date)[DAYS] = (timeMs - (*date)[HOUR]) / MS_PER_DAY;                   // days from year, month, day
37     (*date)[MS] = (*date)[HOUR] % MS_PER_SECOND;                             // ms
38     (*date)[HOUR] = ((*date)[HOUR] - (*date)[MS]) / MS_PER_SECOND;           // s from hour, minutes, second
39     (*date)[SEC] = (*date)[HOUR] % SEC_PER_MINUTE;                           // second
40     (*date)[HOUR] = ((*date)[HOUR] - (*date)[SEC]) / SEC_PER_MINUTE;         // min from hour, minutes
41     (*date)[MIN] = (*date)[HOUR] % SEC_PER_MINUTE;                           // min
42     (*date)[HOUR] = ((*date)[HOUR] - (*date)[MIN]) / SEC_PER_MINUTE;         // hour
43     (*date)[WEEKDAY] = Mod(((*date)[DAYS] + LEAP_NUMBER[0]), DAY_PER_WEEK);  // weekday
44     GetYearFromDays(date);
45 }
46 // static
IsLeap(int64_t year)47 bool DateUtils::IsLeap(int64_t year)
48 {
49     return year % LEAP_NUMBER[0] == 0 && (year % LEAP_NUMBER[1] != 0 || year % LEAP_NUMBER[2] == 0);  // 2: means index
50 }
51 
52 // static
GetDaysInYear(int64_t year)53 int64_t DateUtils::GetDaysInYear(int64_t year)
54 {
55     int64_t number;
56     number = IsLeap(year) ? (DAYS_IN_YEAR + 1) : DAYS_IN_YEAR;
57     return number;
58 }
59 
60 // static
GetDaysFromYear(int64_t year)61 int64_t DateUtils::GetDaysFromYear(int64_t year)
62 {
63     return DAYS_IN_YEAR * (year - YEAR_NUMBER[0]) + FloorDiv(year - YEAR_NUMBER[1], LEAP_NUMBER[0]) -
64            FloorDiv(year - YEAR_NUMBER[2], LEAP_NUMBER[1]) +  // 2: year index
65            FloorDiv(year - YEAR_NUMBER[3], LEAP_NUMBER[2]);   // 3, 2: year index
66 }
67 
68 // static
FloorDiv(int64_t a,int64_t b)69 int64_t DateUtils::FloorDiv(int64_t a, int64_t b)
70 {
71     ASSERT(b != 0);
72     int64_t m = a % b;
73     int64_t res = m < 0 ? ((a - m - b) / b) : ((a - m) / b);
74     return res;
75 }
76 
77 // static
GetYearFromDays(std::array<int64_t,DATE_LENGTH> * date)78 void DateUtils::GetYearFromDays(std::array<int64_t, DATE_LENGTH> *date)
79 {
80     if (date == nullptr) {
81         return;
82     }
83     if (isCached_) {
84         int64_t t = (*date)[DAYS];
85         int64_t newDays = preDays_ + (t - preSumDays_);
86         if (newDays >= 1 && newDays < DAYS_FEBRUARY) {
87             preSumDays_ = t;
88             preDays_ = newDays;
89             (*date)[DAYS] = newDays;
90             (*date)[MONTH] = preMonth_;
91             (*date)[YEAR] = preYear_;
92             return;
93         }
94     }
95     int64_t realDay;
96     int64_t d = (*date)[DAYS];
97     preSumDays_ = d;
98     d += DAYS_1970_TO_0000;                                               // shift from 1970-01-01 to 0000-03-01
99     int64_t era = (d >= 0 ? d : d - DAYS_IN_400_YEARS + 1) / DAYS_IN_400_YEARS;   // an era is a 400 year period
100     int64_t doe = static_cast<int64_t>(d - era * DAYS_IN_400_YEARS);              // days of era
101     int64_t yoe = (doe - doe / DAYS_IN_4_YEARS + doe / DAYS_IN_100_YEARS -
102                    doe / (DAYS_IN_400_YEARS - 1)) / DAYS_IN_YEAR;                 // year of era
103     int64_t y = static_cast<int64_t>(yoe) + era * LEAP_NUMBER[2];
104     int64_t doy = doe - (DAYS_IN_YEAR * yoe + yoe / LEAP_NUMBER[0] -
105                   yoe / LEAP_NUMBER[1]);                                          // days of year
106     int64_t mp = (COEFFICIENT_TO_CIVIL[0] * doy + MONTH_COEFFICIENT) /
107                   COEFFICIENT_TO_CIVIL[1];                                        // [0, 11] / [Mar,Feb] system
108     int64_t month = mp + (mp < MONTH_TRANSFORM[1] ?
109                 MONTH_TRANSFORM[0] : MONTH_TRANSFORM[2]);                         // transform month to civil system
110     int64_t year = y + (month <= MONTH_COEFFICIENT);
111     month -= 1;
112     realDay = doy - (COEFFICIENT_TO_CIVIL[1] * mp + 2) / COEFFICIENT_TO_CIVIL[0] + 1;   // 2: shift from 03-01 to 01-01
113     (*date)[YEAR] = year;
114     (*date)[MONTH] = month;
115     (*date)[DAYS] = realDay;
116     preDays_ = realDay;
117     preMonth_ = month;
118     preYear_ = year;
119     isCached_ = true;
120 }
121 
122 // static
Mod(int64_t a,int b)123 int64_t DateUtils::Mod(int64_t a, int b)
124 {
125     ASSERT(b != 0);
126     int64_t m = a % b;
127     int64_t res = m < 0 ? (m + b) : m;
128     return res;
129 }
130 
131 // static
132 // 20.4.1.11
MakeTime(double hour,double min,double sec,double ms)133 double JSDate::MakeTime(double hour, double min, double sec, double ms)
134 {
135     if (std::isfinite(hour) && std::isfinite(min) && std::isfinite(sec) && std::isfinite(ms)) {
136         double hourInteger = NumberHelper::TruncateDouble(hour);
137         double minInteger = NumberHelper::TruncateDouble(min);
138         double secInteger = NumberHelper::TruncateDouble(sec);
139         double msInteger = NumberHelper::TruncateDouble(ms);
140         return hourInteger * MS_PER_HOUR + minInteger * MS_PER_MINUTE + secInteger * MS_PER_SECOND + msInteger;
141     }
142     return base::NAN_VALUE;
143 }
144 
145 // static
146 // 20.4.1.12
MakeDay(double year,double month,double date)147 double JSDate::MakeDay(double year, double month, double date)
148 {
149     if (std::isfinite(year) && std::isfinite(month) && std::isfinite(date)) {
150         double yearInteger = NumberHelper::TruncateDouble(year);
151         double monthInteger = NumberHelper::TruncateDouble(month);
152         int64_t y = static_cast<int64_t>(yearInteger) + static_cast<int64_t>(monthInteger / MOUTH_PER_YEAR);
153         int64_t m = static_cast<int64_t>(monthInteger) % MOUTH_PER_YEAR;
154         if (m < 0) {
155             m += MOUTH_PER_YEAR;
156             y -= 1;
157         }
158 
159         int64_t days = DateUtils::GetDaysFromYear(y);
160         int index = DateUtils::IsLeap(year) ? 1 : 0;
161         days += DAYS_FROM_MONTH[index][m];
162         return static_cast<double>(days - 1) + NumberHelper::TruncateDouble(date);
163     }
164     return base::NAN_VALUE;
165 }
166 
167 // static
168 // 20.4.1.13
MakeDate(double day,double time)169 double JSDate::MakeDate(double day, double time)
170 {
171     if (std::isfinite(day) && std::isfinite(time)) {
172         return time + day * MS_PER_DAY;
173     }
174     return base::NAN_VALUE;
175 }
176 
177 // static
178 // 20.4.1.14
TimeClip(double time)179 double JSDate::TimeClip(double time)
180 {
181     if (-MAX_TIME_IN_MS <= time && time <= MAX_TIME_IN_MS) {
182         return NumberHelper::TruncateDouble(time);
183     }
184     return base::NAN_VALUE;
185 }
186 
187 // 20.4.1.8
LocalTime(double timeMs) const188 double JSDate::LocalTime(double timeMs) const
189 {
190     return timeMs + GetLocalOffsetFromOS(timeMs, true);
191 }
192 
193 // 20.4.1.9
UTCTime(double timeMs) const194 double JSDate::UTCTime(double timeMs) const
195 {
196     return timeMs - GetLocalOffsetFromOS(timeMs, false);
197 }
198 
199 // static
GetSignedNumFromString(const CString & str,int len,int * index)200 int JSDate::GetSignedNumFromString(const CString &str, int len, int *index)
201 {
202     int res = 0;
203     GetNumFromString(str, len, index, &res);
204     if (str.at(0) == NEG) {
205         return -res;
206     }
207     return res;
208 }
209 
210 // static
GetNumFromString(const CString & str,int len,int * index,int * num)211 bool JSDate::GetNumFromString(const CString &str, int len, int *index, int *num)
212 {
213     int indexStr = *index;
214     char oneByte = 0;
215     while (indexStr < len) {
216         oneByte = str.at(indexStr);
217         if (oneByte >= '0' && oneByte <= '9') {
218             break;
219         }
220         indexStr++;
221     }
222     if (indexStr >= len) {
223         return false;
224     }
225     int value = 0;
226     while (indexStr < len) {
227         oneByte = str.at(indexStr);
228         int val = static_cast<int>(oneByte - '0');
229         if (val >= 0 && val <= NUM_NINE) {
230             value = value * TEN + val;
231             indexStr++;
232         } else {
233             break;
234         }
235     }
236     *num = value;
237     *index = indexStr;
238     return true;
239 }
240 
241 // 20.4.1.7
GetLocalOffsetInMin(const JSThread * thread,int64_t timeMs,bool isLocal)242 int64_t JSDate::GetLocalOffsetInMin(const JSThread *thread, int64_t timeMs, bool isLocal)
243 {
244     if (!isLocal) {
245         return 0;
246     }
247     double localOffset = this->GetLocalOffset().GetDouble();
248     if (localOffset == MAX_DOUBLE) {
249         localOffset = static_cast<double>(GetLocalOffsetFromOS(timeMs, isLocal));
250         SetLocalOffset(thread, JSTaggedValue(localOffset));
251     }
252     return localOffset;
253 }
254 
255 // static
LocalParseStringToMs(const CString & str)256 JSTaggedValue JSDate::LocalParseStringToMs(const CString &str)
257 {
258     int year = 0;
259     int month = 0;
260     int date = 1;
261     int hours = 0;
262     int minutes = 0;
263     int seconds = 0;
264     int ms = 0;
265     int index = 0;
266     int len = static_cast<int>(str.length());
267     bool isLocal = false;
268     CString::size_type indexGmt;
269     CString::size_type indexPlus = CString::npos;
270     int localTime = 0;
271     int localHours = 0;
272     int localMinutes = 0;
273     int64_t localMs = 0;
274     CString::size_type localSpace;
275     localSpace = str.find(' ', index);
276     CString strMonth = str.substr(localSpace + 1, LENGTH_MONTH_NAME);
277     for (int i = 0; i < MOUTH_PER_YEAR; i++) {
278         if (strMonth == MONTH_NAME[i]) {
279             month = i;
280             break;
281         }
282     }
283     index += (LENGTH_MONTH_NAME + 1);
284     GetNumFromString(str, len, &index, &date);
285     GetNumFromString(str, len, &index, &year);
286     indexGmt = str.find("GMT", index);
287     if (indexGmt == CString::npos) {
288         GetNumFromString(str, len, &index, &hours);
289         GetNumFromString(str, len, &index, &minutes);
290         GetNumFromString(str, len, &index, &seconds);
291         isLocal = true;
292         localMs -= (GetLocalOffsetFromOS(localMs, true) * MS_PER_MINUTE);
293     } else {
294         indexPlus = str.find(PLUS, indexGmt);
295         int indexLocal = static_cast<int>(indexGmt);
296         GetNumFromString(str, indexGmt, &index, &hours);
297         GetNumFromString(str, indexGmt, &index, &minutes);
298         GetNumFromString(str, indexGmt, &index, &seconds);
299         GetNumFromString(str, len, &indexLocal, &localTime);
300         localHours = localTime / HUNDRED;
301         localMinutes = localTime % HUNDRED;
302         localMs = static_cast<int64_t>(MakeTime(localHours, localMinutes, 0, 0));
303         if (indexPlus != CString::npos) {
304             localMs = -localMs;
305         }
306     }
307     double day = MakeDay(year, month, date);
308     double time = MakeTime(hours, minutes, seconds, ms);
309     double timeValue = TimeClip(MakeDate(day, time));
310     if (std::isnan(timeValue)) {
311         return JSTaggedValue(timeValue);
312     }
313     if (isLocal && timeValue < CHINA_1901_MS && (-localMs / MS_PER_MINUTE) == CHINA_AFTER_1901_MIN) {
314         timeValue += static_cast<double>(localMs - CHINA_BEFORE_1901_MS);
315     } else {
316         timeValue += localMs;
317     }
318     return JSTaggedValue(timeValue);
319 }
320 
321 // static
UtcParseStringToMs(const CString & str)322 JSTaggedValue JSDate::UtcParseStringToMs(const CString &str)
323 {
324     int year = 0;
325     int month = 0;
326     int date = 1;
327     int hours = 0;
328     int minutes = 0;
329     int seconds = 0;
330     int ms = 0;
331     int index = 0;
332     int len = static_cast<int>(str.length());
333     CString::size_type indexGmt;
334     CString::size_type indexPlus = CString::npos;
335     int localTime = 0;
336     int localHours = 0;
337     int localMinutes = 0;
338     int64_t localMs = 0;
339     bool isLocal = false;
340     GetNumFromString(str, len, &index, &date);
341     CString strMonth = str.substr(index + 1, LENGTH_MONTH_NAME);
342     for (int i = 0; i < MOUTH_PER_YEAR; i++) {
343         if (strMonth == MONTH_NAME[i]) {
344             month = i;
345             break;
346         }
347     }
348     index += (LENGTH_MONTH_NAME + 1);
349     GetNumFromString(str, len, &index, &year);
350     indexGmt = str.find("GMT", index);
351     if (indexGmt == CString::npos) {
352         GetNumFromString(str, len, &index, &hours);
353         GetNumFromString(str, len, &index, &minutes);
354         GetNumFromString(str, len, &index, &seconds);
355         isLocal = true;
356         localMs -= (GetLocalOffsetFromOS(localMs, true) * MS_PER_MINUTE);
357     } else {
358         indexPlus = str.find(PLUS, indexGmt);
359         int indexLocal = static_cast<int>(indexGmt);
360         GetNumFromString(str, indexGmt, &index, &hours);
361         GetNumFromString(str, indexGmt, &index, &minutes);
362         GetNumFromString(str, indexGmt, &index, &seconds);
363         GetNumFromString(str, len, &indexLocal, &localTime);
364         localHours = localTime / HUNDRED;
365         localMinutes = localTime % HUNDRED;
366         localMs = static_cast<int64_t>(MakeTime(localHours, localMinutes, 0, 0));
367         if (indexPlus != CString::npos) {
368             localMs = -localMs;
369         }
370     }
371     double day = MakeDay(year, month, date);
372     double time = MakeTime(hours, minutes, seconds, ms);
373     double timeValue = TimeClip(MakeDate(day, time));
374     if (std::isnan(timeValue)) {
375         return JSTaggedValue(timeValue);
376     }
377     if (isLocal && timeValue < CHINA_1901_MS && (-localMs / MS_PER_MINUTE) == CHINA_AFTER_1901_MIN) {
378         timeValue += static_cast<double>(localMs - CHINA_BEFORE_1901_MS);
379     } else {
380         timeValue += localMs;
381     }
382     return JSTaggedValue(timeValue);
383 }
384 // static
IsoParseStringToMs(const CString & str)385 JSTaggedValue JSDate::IsoParseStringToMs(const CString &str)
386 {
387     char flag = 0;
388     int year;
389     int month = 1;
390     int date = 1;
391     int hours = 0;
392     int minutes = 0;
393     int seconds = 0;
394     int ms = 0;
395     int index = 0;
396     int len = static_cast<int>(str.length());
397     year = GetSignedNumFromString(str, len, &index);
398     CString::size_type indexT = str.find(FLAG_TIME, index);
399     CString::size_type indexZ = str.find(FLAG_UTC, index);
400     CString::size_type indexEndFlag = 0;
401     int64_t localMs = 0;
402     if (indexZ != CString::npos) {
403         indexEndFlag = indexZ;
404     } else if (len >= MIN_LENGTH && str.at(len - INDEX_PLUS_NEG) == NEG) {
405         indexEndFlag = static_cast<CString::size_type>(len - INDEX_PLUS_NEG);
406         flag = NEG;
407     } else if (len >= MIN_LENGTH && str.at(len - INDEX_PLUS_NEG) == PLUS) {
408         indexEndFlag = static_cast<CString::size_type>(len - INDEX_PLUS_NEG);
409         flag = PLUS;
410     }
411     if (indexT != CString::npos) {
412         if (static_cast<int>(indexT) - index == LENGTH_PER_TIME) {
413             GetNumFromString(str, len, &index, &month);
414         } else if (static_cast<int>(indexT) - index == (LENGTH_PER_TIME + LENGTH_PER_TIME)) {
415             GetNumFromString(str, len, &index, &month);
416             GetNumFromString(str, len, &index, &date);
417         }
418         GetNumFromString(str, len, &index, &hours);
419         GetNumFromString(str, len, &index, &minutes);
420         if (indexEndFlag > 0) {
421             if (static_cast<int>(indexEndFlag) - index == LENGTH_PER_TIME) {
422                 GetNumFromString(str, len, &index, &seconds);
423             } else if (static_cast<int>(indexEndFlag) - index == (LENGTH_PER_TIME + LENGTH_PER_TIME + 1)) {
424                 GetNumFromString(str, len, &index, &seconds);
425                 GetNumFromString(str, len, &index, &ms);
426             }
427         } else {
428             if (len - index == LENGTH_PER_TIME) {
429                 GetNumFromString(str, len, &index, &seconds);
430             } else if (len - index == (LENGTH_PER_TIME + LENGTH_PER_TIME + 1)) {
431                 GetNumFromString(str, len, &index, &seconds);
432                 GetNumFromString(str, len, &index, &ms);
433             }
434         }
435     } else {
436         GetNumFromString(str, len, &index, &month);
437         GetNumFromString(str, len, &index, &date);
438     }
439     if (indexEndFlag > 0) {
440         int localHours = 0;
441         int localMinutes = 0;
442         if (indexZ == CString::npos) {
443             GetNumFromString(str, len, &index, &localHours);
444             GetNumFromString(str, len, &index, &localMinutes);
445             if (flag == PLUS) {
446                 localMs = static_cast<int64_t>(-MakeTime(localHours, localMinutes, 0, 0));
447             } else {
448                 localMs = static_cast<int64_t>(MakeTime(localHours, localMinutes, 0, 0));
449             }
450         }
451     }
452     if (indexEndFlag == 0 && indexT != CString::npos) {
453         localMs -= (GetLocalOffsetFromOS(localMs, true) * MS_PER_MINUTE);
454     }
455 
456     double day = MakeDay(year, month - 1, date);
457     double time = MakeTime(hours, minutes, seconds, ms);
458     double timeValue = TimeClip(MakeDate(day, time));
459     if (std::isnan(timeValue)) {
460         return JSTaggedValue(timeValue);
461     }
462     if (flag == 0 && timeValue < CHINA_1901_MS && (-localMs / MS_PER_MINUTE) == CHINA_AFTER_1901_MIN) {
463         timeValue += static_cast<double>(localMs - CHINA_BEFORE_1901_MS);
464     } else {
465         timeValue += localMs;
466     }
467     return JSTaggedValue(timeValue);
468 }
469 
GetTimeFromString(const char * str,int len)470 JSTaggedValue JSDate::GetTimeFromString(const char *str, int len)
471 {
472     int time[TIMEZONE + 1];
473     bool res = DateParse::ParseDateString(str, len, time);
474     if (res) {
475         double day = MakeDay(time[YEAR], time[MONTH], time[DAYS]);
476         double dateTime = MakeTime(time[HOUR], time[MIN], time[SEC], time[MS]);
477         double timeValue = TimeClip(MakeDate(day, dateTime));
478         if (std::isnan(timeValue)) {
479             return JSTaggedValue(timeValue);
480         }
481         int64_t localMs;
482         if (time[TIMEZONE] == INT_MAX) {
483             localMs = GetLocalOffsetFromOS(static_cast<int64_t>(timeValue), true) * MS_PER_MINUTE;
484         } else {
485             localMs = time[TIMEZONE] * MS_PER_SECOND;
486         }
487         timeValue -= localMs;
488         return JSTaggedValue(timeValue);
489     }
490     return JSTaggedValue(base::NAN_VALUE);
491 }
492 
493 // 20.4.3.2 static
Parse(EcmaRuntimeCallInfo * argv)494 JSTaggedValue JSDate::Parse(EcmaRuntimeCallInfo *argv)
495 {
496     ASSERT(argv);
497     JSThread *thread = argv->GetThread();
498     JSHandle<JSTaggedValue> msg = base::BuiltinsBase::GetCallArg(argv, 0);
499     JSHandle<EcmaString> ecmaStr = JSTaggedValue::ToString(thread, msg);
500     RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, JSTaggedValue::Exception());
501     CVector<uint8_t> tmpBuf;
502     EcmaStringAccessor strAccessor(const_cast<EcmaString *>(*ecmaStr));
503     if (strAccessor.IsUtf16()) {
504         return JSTaggedValue(base::NAN_VALUE);
505     }
506     int len = static_cast<int>(strAccessor.GetLength());
507     auto data = reinterpret_cast<const char *>(strAccessor.GetUtf8DataFlat(*ecmaStr, tmpBuf));
508     return GetTimeFromString(data, len);
509 }
510 
511 // 20.4.3.1
Now()512 JSTaggedValue JSDate::Now()
513 {
514     // time from now is in ms.
515     int64_t ans;
516     struct timeval tv {
517     };
518     gettimeofday(&tv, nullptr);
519     ans = static_cast<int64_t>(tv.tv_sec) * MS_PER_SECOND + (tv.tv_usec / MS_PER_SECOND);
520     return JSTaggedValue(static_cast<double>(ans));
521 }
522 
523 // 20.4.4.2 static
UTC(EcmaRuntimeCallInfo * argv)524 JSTaggedValue JSDate::UTC(EcmaRuntimeCallInfo *argv)
525 {
526     double year = 0.0;
527     double month = 0.0;
528     double date = 1.0;
529     double hours = 0.0;
530     double minutes = 0.0;
531     double seconds = 0.0;
532     double ms = 0.0;
533     JSThread *thread = argv->GetThread();
534     JSHandle<JSTaggedValue> yearArg = base::BuiltinsBase::GetCallArg(argv, 0);
535     JSTaggedNumber yearValue = JSTaggedValue::ToNumber(thread, yearArg);
536     RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, JSTaggedValue::Exception());
537     if (yearValue.IsNumber()) {
538         year = yearValue.GetNumber();
539         if (std::isfinite(year) && !yearValue.IsInt()) {
540             year = NumberHelper::TruncateDouble(year);
541         }
542         if (year >= 0 && year <= (HUNDRED - 1)) {
543             year = year + NINETEEN_HUNDRED_YEAR;
544         }
545     } else {
546         year = base::NAN_VALUE;
547     }
548     uint32_t index = 1;
549     uint32_t numArgs = argv->GetArgsNumber();
550     JSTaggedValue res;
551     if (numArgs > index) {
552         JSHandle<JSTaggedValue> value = base::BuiltinsBase::GetCallArg(argv, index);
553         res = JSTaggedValue::ToNumber(thread, value);
554         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, JSTaggedValue::Exception());
555         month = res.GetNumber();
556         index++;
557     }
558     if (numArgs > index) {
559         JSHandle<JSTaggedValue> value = base::BuiltinsBase::GetCallArg(argv, index);
560         res = JSTaggedValue::ToNumber(thread, value);
561         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, JSTaggedValue::Exception());
562         date = res.GetNumber();
563         index++;
564     }
565     if (numArgs > index) {
566         JSHandle<JSTaggedValue> value = base::BuiltinsBase::GetCallArg(argv, index);
567         res = JSTaggedValue::ToNumber(thread, value);
568         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, JSTaggedValue::Exception());
569         hours = res.GetNumber();
570         index++;
571     }
572     if (numArgs > index) {
573         JSHandle<JSTaggedValue> value = base::BuiltinsBase::GetCallArg(argv, index);
574         res = JSTaggedValue::ToNumber(thread, value);
575         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, JSTaggedValue::Exception());
576         minutes = res.GetNumber();
577         index++;
578     }
579     if (numArgs > index) {
580         JSHandle<JSTaggedValue> value = base::BuiltinsBase::GetCallArg(argv, index);
581         res = JSTaggedValue::ToNumber(thread, value);
582         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, JSTaggedValue::Exception());
583         seconds = res.GetNumber();
584         index++;
585     }
586     if (numArgs > index) {
587         JSHandle<JSTaggedValue> value = base::BuiltinsBase::GetCallArg(argv, index);
588         res = JSTaggedValue::ToNumber(thread, value);
589         RETURN_VALUE_IF_ABRUPT_COMPLETION(thread, JSTaggedValue::Exception());
590         ms = res.GetNumber();
591     }
592     double day = MakeDay(year, month, date);
593     double time = MakeTime(hours, minutes, seconds, ms);
594     return JSTaggedValue(TimeClip(MakeDate(day, time)));
595 }
596 
597 // 20.4.4.10
GetTime() const598 JSTaggedValue JSDate::GetTime() const
599 {
600     return GetTimeValue();
601 }
602 
603 // static
StrToTargetLength(const CString & str,int length)604 CString JSDate::StrToTargetLength(const CString &str, int length)
605 {
606     int len = 0;
607     CString sub;
608     if (str[0] == NEG) {
609         sub.reserve(length + 1);
610         ASSERT(str.length() > 0);
611         len = static_cast<int>(str.length() - 1);
612         sub += NEG;
613     } else {
614         sub.reserve(length);
615         len = static_cast<int>(str.length());
616     }
617     int dif = length - len;
618     for (int i = 0; i < dif; i++) {
619         sub += '0';
620     }
621     if (str[0] == NEG) {
622         sub += str.substr(1, len);
623     } else {
624         sub += str;
625     }
626     return sub;
627 }
628 
629 // static
AppendStrToTargetLength(const CString & str,int length,CString & target)630 void JSDate::AppendStrToTargetLength(const CString &str, int length, CString &target)
631 {
632     int len = 0;
633     if (str[0] == NEG) {
634         len = static_cast<int>(str.length() - 1);
635         target += NEG;
636     } else {
637         len = static_cast<int>(str.length());
638     }
639     int dif = length - len;
640     for (int i = 0; i < dif; i++) {
641         target += '0';
642     }
643     if (str[0] == NEG) {
644         target += str.substr(1, len);
645     } else {
646         target += str;
647     }
648 }
649 
GetThisDateValues(JSThread * thread,std::array<int64_t,DATE_LENGTH> * date,bool isLocal) const650 bool JSDate::GetThisDateValues(JSThread *thread, std::array<int64_t, DATE_LENGTH> *date, bool isLocal) const
651 {
652     double timeMs = this->GetTimeValue().GetDouble();
653     if (std::isnan(timeMs)) {
654         return false;
655     }
656     GetDateValues(thread, timeMs, date, isLocal);
657     return true;
658 }
659 
660 // 20.4.4.35
ToDateString(JSThread * thread) const661 JSTaggedValue JSDate::ToDateString(JSThread *thread) const
662 {
663     std::array<int64_t, DATE_LENGTH> fields = {0};
664     if (!GetThisDateValues(thread, &fields, true)) {
665         return JSTaggedValue(base::NAN_VALUE);
666     }
667     CString str;
668     str.reserve(DATE_STRING_LENGTH);
669     str.append(WEEK_DAY_NAME[fields[WEEKDAY]]) // Append weekdy name
670         .append(SPACE_STR) // Append SPACE
671         .append(MONTH_NAME[fields[MONTH]]) // Append mouth name
672         .append(SPACE_STR); // Append SPACE
673     ConvertAndAppend(fields[DAYS], STR_LENGTH_OTHERS, str);
674     str += SPACE;
675     ConvertAndAppend(fields[YEAR], STR_LENGTH_YEAR, str);
676     JSHandle<EcmaString> result = thread->GetEcmaVM()->GetFactory()->NewFromASCII(str);
677     return result.GetTaggedValue();
678 }
679 
680 // static
ToDateString(JSThread * thread,double timeMs)681 CString JSDate::ToDateString(JSThread *thread, double timeMs)
682 {
683     if (std::isnan(timeMs)) {
684         return "Invalid Date";
685     }
686     std::array<int64_t, DATE_LENGTH> fields = {0};
687     GetDateValues(thread, timeMs, &fields, true);
688     CString localTime;
689     int localMin = 0;
690     localMin = GetLocalOffsetFromOS(timeMs, true);
691     if (localMin >= 0) {
692         localTime += PLUS;
693     } else {
694         localTime += NEG;
695         localMin = -localMin;
696     }
697     localTime = localTime + StrToTargetLength(ToCString(localMin / MINUTE_PER_HOUR), STR_LENGTH_OTHERS);
698     localTime = localTime + StrToTargetLength(ToCString(localMin % MINUTE_PER_HOUR), STR_LENGTH_OTHERS);
699     CString str;
700     str.reserve(DATE_CSTRING_LENGTH);
701     str.append(WEEK_DAY_NAME[fields[WEEKDAY]]) // Append weekday name
702         .append(SPACE_STR)  // Append SPACE
703         .append(MONTH_NAME[fields[MONTH]]) // Append mouth name
704         .append(SPACE_STR); // Append SPACE
705     ConvertAndAppend(fields[DAYS], STR_LENGTH_OTHERS, str);
706     str += SPACE;
707     ConvertAndAppend(fields[YEAR], STR_LENGTH_YEAR, str);
708     str += SPACE;
709     ConvertAndAppend(fields[HOUR], STR_LENGTH_OTHERS, str);
710     str += COLON;
711     ConvertAndAppend(fields[MIN], STR_LENGTH_OTHERS, str);
712     str += COLON;
713     ConvertAndAppend(fields[SEC], STR_LENGTH_OTHERS, str);
714     str.append(SPACE_STR) // Append SPACE
715         .append("GMT") // Append GMT
716         .append(localTime); // Append localTime
717     return str;
718 }
719 // 20.4.4.36
ToISOString(JSThread * thread) const720 JSTaggedValue JSDate::ToISOString(JSThread *thread) const
721 {
722     std::array<int64_t, DATE_LENGTH> fields = {0};
723     if (!GetThisDateValues(thread, &fields, false)) {
724         return JSTaggedValue(base::NAN_VALUE);
725     }
726     CString year = ToCString(fields[YEAR]);
727     if (year[0] == NEG) {
728         year = StrToTargetLength(year, STR_LENGTH_YEAR + STR_LENGTH_OTHERS);
729     } else if (year.length() > STR_LENGTH_YEAR) {
730         year = PLUS + StrToTargetLength(year, STR_LENGTH_YEAR + STR_LENGTH_OTHERS);
731     } else {
732         year = StrToTargetLength(year, STR_LENGTH_YEAR);
733     }
734     CString str;
735     str.reserve(ISO_STRING_LENGTH);
736     str.append(year) // Append year
737         .append(NEG_STR); // Append NEG
738     ConvertAndAppend(fields[MONTH] + 1, STR_LENGTH_OTHERS, str);
739     str += NEG;
740     ConvertAndAppend(fields[DAYS], STR_LENGTH_OTHERS, str);
741     str += FLAG_TIME;
742     ConvertAndAppend(fields[HOUR], STR_LENGTH_OTHERS, str);
743     str += COLON;
744     ConvertAndAppend(fields[MIN], STR_LENGTH_OTHERS, str);
745     str += COLON;
746     ConvertAndAppend(fields[SEC], STR_LENGTH_OTHERS, str);
747     str += POINT;
748     ConvertAndAppend(fields[MS], STR_LENGTH_OTHERS + 1, str);
749     str += FLAG_UTC;
750     return thread->GetEcmaVM()->GetFactory()->NewFromASCII(str).GetTaggedValue();
751 }
752 
753 // 20.4.4.41
ToString(JSThread * thread) const754 JSTaggedValue JSDate::ToString(JSThread *thread) const
755 {
756     int localMin = 0;
757     std::array<int64_t, DATE_LENGTH> fields = {0};
758     if (!GetThisDateValues(thread, &fields, true)) {
759         return JSTaggedValue(base::NAN_VALUE);
760     }
761     CString localTime;
762     localMin = GetLocalOffsetFromOS(static_cast<int64_t>(this->GetTimeValue().GetDouble()), true);
763     if (localMin >= 0) {
764         localTime += PLUS;
765     } else {
766         localTime += NEG;
767         localMin = -localMin;
768     }
769     localTime = localTime + StrToTargetLength(ToCString(localMin / MINUTE_PER_HOUR), STR_LENGTH_OTHERS);
770     localTime = localTime + StrToTargetLength(ToCString(localMin % MINUTE_PER_HOUR), STR_LENGTH_OTHERS);
771     CString str;
772     str.reserve(TO_STRING_LENGTH);
773     str.append(WEEK_DAY_NAME[fields[WEEKDAY]]) // Append weekday name
774         .append(SPACE_STR) // Append SPACE
775         .append(MONTH_NAME[fields[MONTH]]) // Append mouth name
776         .append(SPACE_STR); // Append SPACE
777     ConvertAndAppend(fields[DAYS], STR_LENGTH_OTHERS, str);
778     str += SPACE;
779     ConvertAndAppend(fields[YEAR], STR_LENGTH_YEAR, str);
780     str += SPACE;
781     ConvertAndAppend(fields[HOUR], STR_LENGTH_OTHERS, str);
782     str += COLON;
783     ConvertAndAppend(fields[MIN], STR_LENGTH_OTHERS, str);
784     str += COLON;
785     ConvertAndAppend(fields[SEC], STR_LENGTH_OTHERS, str);
786     str.append(SPACE_STR) // Append SPACE
787         .append("GMT") // Append GMT
788         .append(localTime); // Append localTime
789     return thread->GetEcmaVM()->GetFactory()->NewFromASCII(str).GetTaggedValue();
790 }
791 
792 // 20.4.4.42
ToTimeString(JSThread * thread) const793 JSTaggedValue JSDate::ToTimeString(JSThread *thread) const
794 {
795     int localMin = 0;
796     std::array<int64_t, DATE_LENGTH> fields = {0};
797     if (!GetThisDateValues(thread, &fields, true)) {
798         return JSTaggedValue(base::NAN_VALUE);
799     }
800     CString localTime;
801     localMin = GetLocalOffsetFromOS(static_cast<int64_t>(this->GetTimeValue().GetDouble()), true);
802     if (localMin >= 0) {
803         localTime += PLUS;
804     } else {
805         localTime += NEG;
806         localMin = -localMin;
807     }
808     localTime = localTime + StrToTargetLength(ToCString(localMin / MINUTE_PER_HOUR), STR_LENGTH_OTHERS);
809     localTime = localTime + StrToTargetLength(ToCString(localMin % MINUTE_PER_HOUR), STR_LENGTH_OTHERS);
810     CString str;
811     str.reserve(TIME_STRING_LENGTH);
812     ConvertAndAppend(fields[HOUR], STR_LENGTH_OTHERS, str);
813     str += COLON;
814     ConvertAndAppend(fields[MIN], STR_LENGTH_OTHERS, str);
815     str += COLON;
816     ConvertAndAppend(fields[SEC], STR_LENGTH_OTHERS, str);
817     str.append(SPACE_STR) // Append SPACE
818         .append("GMT") // Append GMT
819         .append(localTime); // Append localTime
820     return thread->GetEcmaVM()->GetFactory()->NewFromASCII(str).GetTaggedValue();
821 }
822 
823 // 20.4.4.43
ToUTCString(JSThread * thread) const824 JSTaggedValue JSDate::ToUTCString(JSThread *thread) const
825 {
826     std::array<int64_t, DATE_LENGTH> fields = {0};
827     if (!GetThisDateValues(thread, &fields, false)) {
828         return JSTaggedValue(base::NAN_VALUE);
829     }
830     CString str;
831     str.reserve(UTC_STRING_LENGTH);
832     str.append(WEEK_DAY_NAME[fields[WEEKDAY]]) // Append weekday name
833         .append(COMMA_STR) // Append COMMA
834         .append(SPACE_STR); // Append SPACE
835     ConvertAndAppend(fields[DAYS], STR_LENGTH_OTHERS, str);
836     str.append(SPACE_STR) // Append SPACE
837         .append(MONTH_NAME[fields[MONTH]]) // Append mouth name
838         .append(SPACE_STR); // Append SPACE
839     ConvertAndAppend(fields[YEAR], STR_LENGTH_YEAR, str);
840     str += SPACE;
841     ConvertAndAppend(fields[HOUR], STR_LENGTH_OTHERS, str);
842     str += COLON;
843     ConvertAndAppend(fields[MIN], STR_LENGTH_OTHERS, str);
844     str += COLON;
845     ConvertAndAppend(fields[SEC], STR_LENGTH_OTHERS, str);
846     str.append(SPACE_STR) // Append SPACE
847         .append("GMT"); // Append GMT
848     return thread->GetEcmaVM()->GetFactory()->NewFromASCII(str).GetTaggedValue();
849 }
850 
851 // 20.4.4.44
ValueOf() const852 JSTaggedValue JSDate::ValueOf() const
853 {
854     return this->GetTimeValue();
855 }
856 
857 // static
GetDateValues(JSThread * thread,double timeMs,std::array<int64_t,DATE_LENGTH> * date,bool isLocal)858 void JSDate::GetDateValues(JSThread *thread, double timeMs, std::array<int64_t, DATE_LENGTH> *date, bool isLocal)
859 {
860     int64_t tz = 0;
861     int64_t timeMsInt = static_cast<int64_t>(timeMs);
862     if (isLocal) {  // timezone offset
863         tz = GetLocalOffsetFromOS(timeMsInt, isLocal);
864         timeMsInt += tz * MS_PER_SECOND * SEC_PER_MINUTE;
865     }
866 
867     thread->GetDateUtils()->TransferTimeToDate(timeMsInt, date);
868     (*date)[TIMEZONE] = -tz;
869 }
870 
GetDateValue(JSThread * thread,double timeMs,uint8_t code,bool isLocal) const871 double JSDate::GetDateValue(JSThread *thread, double timeMs, uint8_t code, bool isLocal) const
872 {
873     if (std::isnan(timeMs)) {
874         return base::NAN_VALUE;
875     }
876     std::array<int64_t, DATE_LENGTH> date = {0};
877     GetDateValues(thread, timeMs, &date, isLocal);
878     return static_cast<double>(date[code]);
879 }
880 
SetDateValue(EcmaRuntimeCallInfo * argv,uint32_t code,bool isLocal) const881 JSTaggedValue JSDate::SetDateValue(EcmaRuntimeCallInfo *argv, uint32_t code, bool isLocal) const
882 {
883     // get date values.
884     std::array<int64_t, DATE_LENGTH> date = {0};
885     double timeMs = this->GetTimeValue().GetDouble();
886 
887     // get values from argv.
888     uint32_t argc = argv->GetArgsNumber();
889     if (argc == 0) {
890         return JSTaggedValue(base::NAN_VALUE);
891     }
892 
893     uint32_t firstValue = code & CODE_FLAG;
894     uint32_t endValue = (code >> CODE_4_BIT) & CODE_FLAG;
895     uint32_t count = endValue - firstValue;
896 
897     if (argc < count) {
898         count = argc;
899     }
900     JSThread *thread = argv->GetThread();
901     if (std::isnan(timeMs) && firstValue == 0) {
902         timeMs = 0.0;
903         GetDateValues(thread, timeMs, &date, false);
904     } else {
905         GetDateValues(thread, timeMs, &date, isLocal);
906     }
907     for (uint32_t i = 0; i < count; i++) {
908         JSHandle<JSTaggedValue> value = base::BuiltinsBase::GetCallArg(argv, i);
909         JSTaggedNumber res = JSTaggedValue::ToNumber(thread, value);
910         RETURN_EXCEPTION_IF_ABRUPT_COMPLETION(thread);
911         double temp = res.GetNumber();
912         if (std::isnan(temp)) {
913             return JSTaggedValue(base::NAN_VALUE);
914         }
915         date[firstValue + i] = NumberHelper::TruncateDouble(temp);
916     }
917     // set date values.
918     return JSTaggedValue(SetDateValues(&date, isLocal));
919 }
920 
921 // static
SetDateValues(const std::array<int64_t,DATE_LENGTH> * date,bool isLocal)922 double JSDate::SetDateValues(const std::array<int64_t, DATE_LENGTH> *date, bool isLocal)
923 {
924     int64_t month = DateUtils::Mod((*date)[MONTH], MONTH_PER_YEAR);
925     int64_t year = (*date)[YEAR] + ((*date)[MONTH] - month) / MONTH_PER_YEAR;
926     int64_t days = DateUtils::GetDaysFromYear(year);
927     int index = DateUtils::IsLeap(year) ? 1 : 0;
928     days += DAYS_FROM_MONTH[index][month];
929 
930     days += (*date)[DAYS] - 1;
931     int64_t millisecond =
932         (((*date)[HOUR] * MIN_PER_HOUR + (*date)[MIN]) * SEC_PER_MINUTE + (*date)[SEC]) * MS_PER_SECOND + (*date)[MS];
933     int64_t result = days * MS_PER_DAY + millisecond;
934     if (isLocal) {
935         int64_t offset = GetLocalOffsetFromOS(result, isLocal) * SEC_PER_MINUTE * MS_PER_SECOND;
936         result -= offset;
937     }
938     return TimeClip(result);
939 }
940 
SetDateValues(int64_t year,int64_t month,int64_t day)941 double JSDate::SetDateValues(int64_t year, int64_t month, int64_t day)
942 {
943     if (year >= 0 && year < HUNDRED) {
944         year += NINETEEN_HUNDRED_YEAR;
945     }
946     int64_t m = DateUtils::Mod(month, MONTH_PER_YEAR);
947     int64_t y = year + (month - m) / MONTH_PER_YEAR;
948     int64_t d = DateUtils::GetDaysFromYear(y);
949     int index = DateUtils::IsLeap(y) ? 1 : 0;
950     d += DAYS_FROM_MONTH[index][m] + day - 1;
951     int64_t result = d * MS_PER_DAY;
952 
953     int64_t offset = GetLocalOffsetFromOS(result, true) * SEC_PER_MINUTE * MS_PER_SECOND;
954     result -= offset;
955     return TimeClip(result);
956 }
957 }  // namespace panda::ecmascript
958