forked from cesarParra/expression
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDateAndTimeFunctions.cls
More file actions
916 lines (819 loc) · 32.6 KB
/
Copy pathDateAndTimeFunctions.cls
File metadata and controls
916 lines (819 loc) · 32.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
/**
* @description Repository of functions that can be used in expressions.
* @group Date and Time
* @function-repository true
* @display-icon utility:date_input
*/
public with sharing class DateAndTimeFunctions {
private static final Map<String, StandardFunction> FUNCTIONS = new Map<String, StandardFunction> {
'ADDDAYS' => new DateAndTimeFunctions.AddDaysFn(),
'ADDMONTHS' => new DateAndTimeFunctions.AddMonthsFn(),
'DATE' => new DateAndTimeFunctions.DateFn(),
'DATETIME' => new DateAndTimeFunctions.DatetimeFn(),
'DAY' => new DateAndTimeFunctions.DayFn(),
'DAYOFYEAR' => new DateAndTimeFunctions.DayOfYearFn(),
'NOW' => new DateAndTimeFunctions.NowFn(),
'DATEVALUE' => new DateAndTimeFunctions.DateValueFn(),
'DATETIMEVALUE' => new DateAndTimeFunctions.DateTimeValueFn(),
'TODAY' => new DateAndTimeFunctions.TodayFn(),
'MILLISECOND' => new DateAndTimeFunctions.MillisecondFn(),
'MINUTE' => new DateAndTimeFunctions.MinuteFn(),
'SECOND' => new DateAndTimeFunctions.SecondFn(),
'HOUR' => new DateAndTimeFunctions.HourFn(),
'TIMEVALUE' => new DateAndTimeFunctions.TimeValueFn(),
'TIMENOW' => new DateAndTimeFunctions.TimeNowFn(),
'ISOWEEK' => new DateAndTimeFunctions.IsoWeek(),
'ISOYEAR' => new DateAndTimeFunctions.IsoYear(),
'YEAR' => new DateAndTimeFunctions.YearFn(),
'FROMUNIXTIME' => new DateAndTimeFunctions.FromUnixTimeFn(),
'UNIXTIMESTAMP' => new UnixTimeStampFn(),
'WEEKDAY' => new WeekdayFn(),
'FORMATDURATION' => new FormatDuration(),
'MONTH' => new MonthFn(),
'DATETIMEFORMAT' => new DateTimeFormatFn(),
'DATETODATETIME' => new DateToDateTimeFn(),
'DAYSBETWEEN' => new DaysBetween()
};
public class DateAndTimeFunctionsProvider implements FunctionProvider {
public Map<String, StandardFunction> getFunctions() {
return FUNCTIONS;
}
}
private enum TimeType {
MILLISECOND, MINUTE, SECOND, HOUR_FN
}
/**
* @description Returns a date that is a specified number of days before or after a given date.
*
* Accepts 2 arguments: the date and the number of days to add.
* @function ADDDAYS
* @example
* ADDDAYS(DATE(2020, 1, 1), 1) // 2020-01-02
*/
private class AddDaysFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object startDate = evaluate(arguments.get(0));
if (!(startDate instanceof Date)) {
throw new FunctionExecutionException(
'Error executing "ADDDAYS" function: the argument must evaluate to a date value.'
);
}
Object daysToAdd = evaluate(arguments.get(1));
if (!(daysToAdd instanceof Decimal)) {
throw new FunctionExecutionException(
'Error executing "ADDDAYS" function: the argument must evaluate to a number value.'
);
}
return ((Date)startDate).addDays(((Decimal)daysToAdd).intValue());
}
public override Arity getArity() {
return Arity.exactly(2);
}
}
/**
* @description Returns a date that is a specified number of months before or after a given date.
*
* Accepts 2 arguments: the date and the number of months to add.
* @function ADDMONTHS
* @example
* ADDMONTHS(DATE(2020, 1, 1), 1) // 2020-02-01
*/
private class AddMonthsFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object startMonth = evaluate(arguments.get(0));
if (!(startMonth instanceof Date)) {
throw new FunctionExecutionException(
'Error executing "ADDMONTHS" function: the argument must evaluate to a date value.'
);
}
Object monthsToAdd = evaluate(arguments.get(1));
if (!(monthsToAdd instanceof Decimal)) {
throw new FunctionExecutionException(
'Error executing "ADDMONTHS" function: the argument must evaluate to a number value.'
);
}
return ((Date)startMonth).addMonths(((Decimal)monthsToAdd).intValue());
}
public override Arity getArity() {
return Arity.exactly(2);
}
}
/**
* @description Returns a date value from the provided year, month, and day values.
*
* Accepts 3 arguments: the year, month, and day.
* @function DATE
* @example
* DATE(2020, 1, 1) // 2020-01-01
*/
private class DateFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object year = evaluate(arguments.get(0));
if (!(year instanceof Decimal)) {
throw new FunctionExecutionException(
'Error executing "DATE" function: the argument must evaluate to a number value.'
);
}
Object month = evaluate(arguments.get(1));
if (!(month instanceof Decimal)) {
throw new FunctionExecutionException(
'Error executing "DATE"" function: the argument must evaluate to a number value.'
);
}
Object day = evaluate(arguments.get(2));
if (!(day instanceof Decimal)) {
throw new FunctionExecutionException(
'Error executing "DATE" function: the argument must evaluate to a number value.'
);
}
return Date.newInstance(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day));
}
public override Arity getArity() {
return Arity.exactly(3);
}
}
/**
* @description Returns a datetime value from the provided year, month, day, hour, minute, and second values.
*
* Accepts 6 arguments: the year, month, day, hour, minute, and second.
* @function DATETIME
* @example
* DATETIME(2020, 1, 1, 12, 0, 0) // 2020-01-01 12:00:00
*/
private class DatetimeFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object year = evaluate(arguments.get(0));
if (!(year instanceof Decimal)) {
throw new FunctionExecutionException(
'Error executing "DATETIME" function: the argument must evaluate to a number value.'
);
}
Object month = evaluate(arguments.get(1));
if (!(month instanceof Decimal)) {
throw new FunctionExecutionException(
'Error executing "DATETIME"" function: the argument must evaluate to a number value.'
);
}
Object day = evaluate(arguments.get(2));
if (!(day instanceof Decimal)) {
throw new FunctionExecutionException(
'Error executing "DATETIME" function: the argument must evaluate to a number value.'
);
}
Object hour = evaluate(arguments.get(3));
if (!(hour instanceof Decimal)) {
throw new FunctionExecutionException(
'Error executing "DATETIME" function: the argument must evaluate to a number value.'
);
}
Object minute = evaluate(arguments.get(4));
if (!(minute instanceof Decimal)) {
throw new FunctionExecutionException(
'Error executing "DATETIME" function: the argument must evaluate to a number value.'
);
}
Object second = evaluate(arguments.get(5));
if (!(second instanceof Decimal)) {
throw new FunctionExecutionException(
'Error executing "DATETIME" function: the argument must evaluate to a number value.'
);
}
return Datetime.newInstance(
Integer.valueOf(year),
Integer.valueOf(month),
Integer.valueOf(day),
Integer.valueOf(hour),
Integer.valueOf(minute),
Integer.valueOf(second)
);
}
public override Arity getArity() {
return Arity.exactly(6);
}
}
/**
* @description Returns the day of the month, a number from 1 to 31.
*
* Accepts 1 argument: the date to evaluate.
* @function DAY
* @example
* DAY(DATE(2020, 1, 1)) // 1
*/
private class DayFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object dateValue = evaluate(arguments.get(0));
if (!(dateValue instanceof Date)) {
throw new FunctionExecutionException(
'Error executing "DAY" function: the argument must evaluate to a date value.'
);
}
return ((Date)dateValue).day();
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Returns the day of the year, a number from 1 to 366.
*
* Accepts 1 argument: the date to evaluate.
* @function DAYOFYEAR
* @example
* DAYOFYEAR(DATE(2020, 1, 1)) // 1
*/
private class DayOfYearFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object dateValue = evaluate(arguments.get(0));
if (!(dateValue instanceof Date)) {
throw new FunctionExecutionException(
'Error executing "DAYOFYEAR" function: the argument must evaluate to a date value.'
);
}
return ((Date)dateValue).dayOfYear();
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Returns the current Datetime in the GMT time zone.
*
* Accepts no arguments.
* @function NOW
* @example
* NOW() // 2020-01-01 00:00:00
*/
private class NowFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
return Datetime.now();
}
public override Arity getArity() {
return Arity.exactly(0);
}
}
/**
* @description Returns a date value from a string representation of a date or a datetime.
*
* Accepts 1 argument: the date as a string or datetime.
* @function DATEVALUE
* @example
* DATEVALUE("2020-01-01") // 2020-01-01
*/
private class DateValueFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
// Expect the expression to either be a text or a datetime
Object expression = evaluate(arguments.get(0));
if (!(expression instanceof String) && !(expression instanceof Datetime)) {
throw new FunctionExecutionException(
'Error executing "DATEVALUE" function: the argument must evaluate to a string or datetime value.'
);
}
if (expression instanceof String) {
return Date.valueOf((String)expression);
} else {
return ((Datetime)expression).date();
}
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Returns a datetime value from a string representation of a date time.
*
* Accepts 1 argument: the date time as a string.
* @function DATETIMEVALUE
* @example
* DATETIMEVALUE("2020-01-01 00:00:00") // 2020-01-01 00:00:00
*/
private class DateTimeValueFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object expression = evaluate(arguments.get(0));
if (!(expression instanceof String)) {
throw new FunctionExecutionException(
'Error executing "DATETIMEVALUE" function: the argument must evaluate to a string value.'
);
}
return Datetime.valueOf((String)expression);
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Returns the current date.
*
* Accepts no arguments.
* @function TODAY
* @example
* TODAY() // 2020-01-01
*/
private class TodayFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
return Date.today();
}
public override Arity getArity() {
return Arity.exactly(0);
}
}
private virtual class TimeFn extends StandardFunction {
private final String fnName;
private final TimeType type;
public TimeFn(String fnName, TimeType type) {
this.fnName = fnName;
this.type = type;
}
public override Object call(List<Expr> arguments) {
Object timeValue = evaluate(arguments.get(0));
if (!(timeValue instanceof Time)) {
throw new FunctionExecutionException(
'Error executing ' + fnName + ' function: the argument must evaluate to a time value.'
);
}
if (type == TimeType.MILLISECOND) {
return ((Time)timeValue).millisecond();
} else if (type == TimeType.MINUTE) {
return ((Time)timeValue).minute();
} else if (type == TimeType.SECOND) {
return ((Time)timeValue).second();
} else {
return ((Time)timeValue).hour();
}
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Returns the millisecond value of a provided time.
*
* Accepts 1 argument: the time to evaluate.
* @function MILLISECOND
* @example
* MILLISECOND(TIMEVALUE("12:00:00.123")) // 123
*/
private class MillisecondFn extends TimeFn {
private MillisecondFn() {
super('MILLISECOND', TimeType.MILLISECOND);
}
}
/**
* @description Returns the second value of a provided time.
*
* Accepts 1 argument: the time to evaluate.
* @function SECOND
* @example
* SECOND(TIMEVALUE("12:00:45")) // 45
*/
private class SecondFn extends TimeFn {
private SecondFn() {
super('SECOND', TimeType.SECOND);
}
}
/**
* @description Returns the minute value of a provided time.
*
* Accepts 1 argument: the time to evaluate.
* @function MINUTE
* @example
* MINUTE(TIMEVALUE("12:10:00")) // 10
*/
private class MinuteFn extends TimeFn {
private MinuteFn() {
super('MINUTE', TimeType.MINUTE);
}
}
/**
* @description Returns the hour value of a provided time.
*
* Accepts 1 argument: the time to evaluate.
* @function HOUR
* @example
* HOUR(TIMEVALUE("12:00:00")) // 12
*/
private class HourFn extends TimeFn {
private HourFn() {
super('HOUR', TimeType.HOUR_FN);
}
}
/**
* @description Returns a time value from a datetime or from a string representation of a datetime.
*
* Accepts 1 argument: the datetime or string in datetime format to evaluate.
* @function TIMEVALUE
* @example
* TIMEVALUE(DATETIMEVALUE("2020-01-01 12:00:00")) // 12:00:00
*/
private class TimeValueFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object dateTimeOrText = evaluate(arguments.get(0));
if (!(dateTimeOrText instanceof String) && !(dateTimeOrText instanceof Datetime)) {
throw new FunctionExecutionException(
'Error executing "TIMEVALUE" function: the argument must evaluate to a string or datetime value.'
);
}
if (dateTimeOrText instanceof String) {
// A received string should be in the format of HH:mm:ss.SSS
String[] parts = ((String)dateTimeOrText).split(':');
if (parts.size() != 3) {
throw new FunctionExecutionException(
'Error executing "TIMEVALUE" function: the argument must evaluate to a string in the format of HH:mm:ss.SSS.'
);
}
Integer hours = Integer.valueOf(parts[0]);
Integer minutes = Integer.valueOf(parts[1]);
String secondsMilli = parts[2];
if (secondsMilli.contains('.')) {
String[] secondsMilliParts = secondsMilli.split('\\.');
Integer seconds = Integer.valueOf(secondsMilliParts[0]);
Integer milliseconds = Integer.valueOf(secondsMilliParts[1]);
return Time.newInstance(hours, minutes, seconds, milliseconds);
} else {
Integer seconds = Integer.valueOf(secondsMilli);
return Time.newInstance(hours, minutes, seconds, 0);
}
} else {
return ((Datetime)dateTimeOrText).time();
}
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Returns the current time.
*
* Accepts no arguments.
* @function TIMENOW
* @example
* TIMENOW() // 12:00:00
*/
private class TimeNowFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
return Datetime.now().time();
}
public override Arity getArity() {
return Arity.exactly(0);
}
}
/**
* @description Returns the ISO week number of the year for a given date.
*
* Accepts 1 argument: the date to evaluate.
* @function ISOWEEK
* @example
* ISOWEEK(DATE(2020, 1, 1)) // 1
*/
private class IsoWeek extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object dateValue = evaluate(arguments.get(0));
if (!(dateValue instanceof Date)) {
throw new FunctionExecutionException(
'Error executing "ISOWEEK" function: the argument must evaluate to a date value.'
);
}
return getIsoWeekNumber((Date) dateValue);
}
public override Arity getArity() {
return Arity.exactly(1);
}
// --- ISO WEEK IMPLEMENTATION ---
private Integer getIsoWeekNumber(Date inputDate) {
Integer isoWeekday = getIsoWeekday(inputDate); // Monday=1 ... Sunday=7
Integer week = floorDiv(inputDate.dayOfYear() - isoWeekday + 10, 7);
if (week < 1) {
return getIsoWeeksInYear(inputDate.year() - 1);
}
Integer weeksInYear = getIsoWeeksInYear(inputDate.year());
if (week > weeksInYear) {
return 1;
}
return week;
}
private Integer getIsoWeeksInYear(Integer year) {
// Dec 28 is always in the last ISO week
Date dec28 = Date.newInstance(year, 12, 28);
Integer isoWeekday = getIsoWeekday(dec28);
return floorDiv(dec28.dayOfYear() - isoWeekday + 10, 7);
}
private Integer getIsoWeekday(Date inputDate) {
// 1900-01-01 was Monday
Integer diff = Date.newInstance(1900, 1, 1).daysBetween(inputDate);
Integer mod = Math.mod(diff, 7);
if (mod < 0) {
mod += 7;
}
return mod + 1;
}
private Integer floorDiv(Integer a, Integer b) {
Integer result = a / b;
if (a < 0 && Math.mod(a, b) != 0) {
result--;
}
return result;
}
}
/**
* @description Returns the ISO year number for a given date.
*
* Accepts 1 argument: the date to evaluate.
* @function ISOYEAR
* @example
* ISOYEAR(DATE(2020, 1, 1)) // 2020
*/
private class IsoYear extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object dateValue = evaluate(arguments.get(0));
if (!(dateValue instanceof Date)) {
throw new FunctionExecutionException(
'Error executing "ISOYEAR" function: the argument must evaluate to a date value.'
);
}
return Integer.valueOf(Datetime.newInstanceGmt((Date)dateValue, Time.newInstance(0, 0, 0, 0)).format('Y'));
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Returns the year value of a provided date.
*
* Accepts 1 argument: the date to evaluate.
* @function YEAR
* @example
* YEAR(DATE(2020, 1, 1)) // 2020
*/
private class YearFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object dateValue = evaluate(arguments.get(0));
if (!(dateValue instanceof Date)) {
throw new FunctionExecutionException(
'Error executing "YEAR" function: the argument must evaluate to a date value.'
);
}
return ((Date)dateValue).year();
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Returns the GMT Datetime from a Unix timestamp.
*
* Accepts 1 argument: the Unix timestamp to evaluate.
* @function FROMUNIXTIME
* @example
* FROMUNIXTIME(1577836800) // 2020-01-01 00:00:00
*/
private class FromUnixTimeFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object unixTime = evaluate(arguments.get(0));
if (!(unixTime instanceof Decimal)) {
throw new FunctionExecutionException(
'Error executing "FROMUNIXTIME" function: the argument must evaluate to a number value.'
);
}
Long timeStamp = ((Decimal)unixTime).longValue() * 1000;
Datetime gmtDatetime = Datetime.newInstance(timeStamp);
return gmtDatetime;
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Returns the number of seconds since 1 Jan 1970 for the given date or datetime,
* or number of seconds in the day for a time.
*
* Values are returned in the GMT time zone.
*
* Accepts 1 argument: the date, datetime, or time to evaluate.
* @function UNIXTIMESTAMP
* @example
* UNIXTIMESTAMP(DATE(2020, 1, 1)) // 1577836800
*/
private class UnixTimeStampFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object dateOrDateTimeOrTime = evaluate(arguments.get(0));
if (!(dateOrDateTimeOrTime instanceof Date) && !(dateOrDateTimeOrTime instanceof Datetime) && !(dateOrDateTimeOrTime instanceof Time)) {
throw new FunctionExecutionException(
'Error executing "UNIXTIMESTAMP" function: the argument must evaluate to a date, datetime or time value.'
);
}
if (dateOrDateTimeOrTime instanceof Date) {
// Convert to datetime first
Datetime gmtDatetime = Datetime.newInstanceGmt((Date)dateOrDateTimeOrTime, Time.newInstance(0, 0, 0, 0));
return gmtDatetime.getTime() / 1000;
} else if (dateOrDateTimeOrTime instanceof Datetime) {
Datetime gmtDateTime = Datetime.newInstanceGmt(((Datetime)dateOrDateTimeOrTime).date(), ((Datetime)dateOrDateTimeOrTime).time());
return gmtDateTime.getTime() / 1000;
} else {
// Calculate the number of seconds in the day for a given time
return ((Time)dateOrDateTimeOrTime).hour() * 3600 + ((Time)dateOrDateTimeOrTime).minute() * 60 + ((Time)dateOrDateTimeOrTime).second();
}
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Returns the day of the week for the given date,
* using 1 for Sunday, 2 for Monday, through 7 for Saturday.
*
* Accepts 1 argument: the date to evaluate.
* @function WEEKDAY
* @example
* WEEKDAY(DATE(2020, 1, 1)) // 2
*/
private class WeekdayFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
Object dateValue = evaluate(arguments.get(0));
if (!(dateValue instanceof Date)) {
throw new FunctionExecutionException(
'Error executing "WEEKDAY" function: the argument must evaluate to a date value.'
);
}
Date dateObj = (Date)dateValue;
return Integer.valueOf(Datetime.newInstanceGmt(
dateObj.year(),
dateObj.month(),
dateObj.day(),
0,
0,
0
).format('u'));
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Calculates the difference between 2 Times or 2 DateTimes
* and formats it as "HH:MM:SS".
*
* Accepts 2 arguments: either 2 Times or 2 DateTimes.
*
* Note that the order of the argument is not important, the
* function will always return a positive duration.
* @function FORMATDURATION
* @example
* FORMATDURATION(TIMEVALUE("12:00:00"), TIMEVALUE("12:00:01")) // 00:00:01
*/
private class FormatDuration extends StandardFunction {
public override Object call(List<Expr> arguments) {
Datetime startDateTime;
Datetime endDateTime;
// Expects either 2 Times or 2 DateTimes
Object startVal = evaluate(arguments.get(0));
if (startVal instanceof Time) {
Time startTime = (Time)startVal;
// Check that the second value is also a Time
Object endVal = evaluate(arguments.get(1));
if (!(endVal instanceof Time)) {
throw new FunctionExecutionException(
'Error executing "FORMATDURATION" function: the second argument must evaluate to a time value.'
);
}
Time endTime = (Time)endVal;
// Convert both times to date times
startDateTime = Datetime.newInstanceGmt(Date.newInstance(0, 1, 1), startTime);
endDateTime = Datetime.newInstanceGmt(Date.newInstance(0, 1, 1), endTime);
} else if (startVal instanceof Datetime) {
startDateTime = (Datetime)startVal;
// Check that the second value is also a Datetime
Object endVal = evaluate(arguments.get(1));
if (!(endVal instanceof Datetime)) {
throw new FunctionExecutionException(
'Error executing "FORMATDURATION" function: the second argument must evaluate to a datetime value.'
);
}
endDateTime = (Datetime)endVal;
} else {
throw new FunctionExecutionException(
'Error executing "FORMATDURATION" function: the first argument must evaluate to a time or datetime value.'
);
}
// Calculate the difference between the two
Long differenceInMs = Math.abs(endDateTime.getTime() - startDateTime.getTime());
Integer hours = (Integer)Math.floor(differenceInMs / 1000 / 60 / 60);
Integer minutes = (Integer)Math.floor((differenceInMs - hours * 1000 * 60 * 60) / 1000 / 60);
Integer seconds = (Integer)Math.floor((differenceInMs - hours * 1000 * 60 * 60 - minutes * 1000 * 60) / 1000);
// Format in HH:MM:SS
// Use StringUtils.leftPad if necessary
return StringUtils.leftPad(String.valueOf(hours), 2, '0') +
':' +
StringUtils.leftPad(String.valueOf(minutes), 2, '0') +
':' +
StringUtils.leftPad(String.valueOf(seconds), 2, '0');
}
public override Arity getArity() {
return Arity.exactly(2);
}
}
/**
* @description Returns the month, a number between 1 and 12 (December) in number format of a given date.
*
* Accepts 1 argument: the date to evaluate.
* @function MONTH
* @example
* MONTH(DATE(2020, 1, 1)) // 1
*/
private class MonthFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
// Expect a Date
Object dateValue = evaluate(arguments.get(0));
if (!(dateValue instanceof Date)) {
throw new FunctionExecutionException(
'Error executing "MONTH" function: the argument must evaluate to a date value.'
);
}
return ((Date)dateValue).month();
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Formats a DateTime into a string using the provided format.
*
* Accepts 2 arguments: the DateTime to format and the format string.
* @function DATETIMEFORMAT
* @example
* DATETIMEFORMAT(DATETIMEVALUE("2020-01-01 12:00:00"), "yyyy-MM-dd") // 2020-01-01
*/
private class DateTimeFormatFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
// Expect a DateTime
Object dateTimeValue = evaluate(arguments.get(0));
if (!(dateTimeValue instanceof Datetime)) {
throw new FunctionExecutionException(
'Error executing "DATETIMEFORMAT" function: the argument must evaluate to a datetime value.'
);
}
// Expect a format string
Object formatValue = evaluate(arguments.get(1));
if (!(formatValue instanceof String)) {
throw new FunctionExecutionException(
'Error executing "DATETIMEFORMAT" function: the argument must evaluate to a string value.'
);
}
return ((Datetime)dateTimeValue).format((String)formatValue);
}
public override Arity getArity() {
return Arity.exactly(2);
}
}
/**
* @description Converts a Date to a Datetime.
*
* Accepts 1 argument: the Date to convert.
* @function DATETODATETIME
* @example
* DATETODATETIME(DATE(2020, 1, 1)) // 2020-01-01 00:00:00
*/
private class DateToDateTimeFn extends StandardFunction {
public override Object call(List<Expr> arguments) {
// Expect a Date
Object dateValue = evaluate(arguments.get(0));
if (!(dateValue instanceof Date)) {
throw new FunctionExecutionException(
'Error executing "DATETODATETIME" function: the argument must evaluate to a date value.'
);
}
return Datetime.newInstance((Date)dateValue, Time.newInstance(0, 0, 0, 0));
}
public override Arity getArity() {
return Arity.exactly(1);
}
}
/**
* @description Returns the number of days between two dates.
*
* Accepts 2 arguments: the first date and the second date.
* @function DAYSBETWEEN
* @example
* DAYSBETWEEN(DATE(2020, 1, 1), DATE(2020, 1, 2)) // 1
*/
private class DaysBetween extends StandardFunction {
public override Object call(List<Expr> arguments) {
// Expect a Date
Object dateValue = evaluate(arguments.get(0));
if (!(dateValue instanceof Date)) {
throw new FunctionExecutionException(
'Error executing "DAYSBETWEEN" function: the argument must evaluate to a date value.'
);
}
// Expect a Date
Object dateValue2 = evaluate(arguments.get(1));
if (!(dateValue2 instanceof Date)) {
throw new FunctionExecutionException(
'Error executing "DAYSBETWEEN" function: the argument must evaluate to a date value.'
);
}
return ((Date)dateValue).daysBetween((Date)dateValue2);
}
public override Arity getArity() {
return Arity.exactly(2);
}
}
}