github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/datetime/add_subtract.go (about) 1 package datetime 2 3 import ( 4 "context" 5 6 "github.com/MontFerret/ferret/pkg/runtime/core" 7 "github.com/MontFerret/ferret/pkg/runtime/values" 8 "github.com/MontFerret/ferret/pkg/runtime/values/types" 9 ) 10 11 var ( 12 emptyDateTime values.DateTime 13 emptyInt values.Int 14 emptyString values.String 15 ) 16 17 // DATE_ADD adds amount given in unit to date. 18 // The following units are available: 19 // * y, year, year 20 // * m, month, months 21 // * w, week, weeks 22 // * d, day, days 23 // * h, hour, hours 24 // * i, minute, minutes 25 // * s, second, seconds 26 // * f, millisecond, milliseconds 27 // @param {DateTime} date - Source date. 28 // @param {Int} amount - Amount of units 29 // @param {String} unit - Unit. 30 // @return {DateTime} - Calculated date. 31 func DateAdd(_ context.Context, args ...core.Value) (core.Value, error) { 32 date, amount, unit, err := getArgs(args) 33 if err != nil { 34 return values.None, err 35 } 36 37 u, err := UnitFromString(unit.String()) 38 if err != nil { 39 return values.None, err 40 } 41 42 tm := AddUnit(date.Time, int(amount), u) 43 44 return values.NewDateTime(tm), nil 45 } 46 47 // DATE_SUBTRACT subtract amount given in unit to date. 48 // The following units are available: 49 // * y, year, year 50 // * m, month, months 51 // * w, week, weeks 52 // * d, day, days 53 // * h, hour, hours 54 // * i, minute, minutes 55 // * s, second, seconds 56 // * f, millisecond, milliseconds 57 // @param {DateTime} date - source date. 58 // @param {Int} amount - amount of units 59 // @param {String} unit - unit. 60 // @return {DateTime} - calculated date. 61 func DateSubtract(_ context.Context, args ...core.Value) (core.Value, error) { 62 date, amount, unit, err := getArgs(args) 63 if err != nil { 64 return values.None, err 65 } 66 67 u, err := UnitFromString(unit.String()) 68 if err != nil { 69 return values.None, err 70 } 71 72 tm := AddUnit(date.Time, -1*int(amount), u) 73 74 return values.NewDateTime(tm), nil 75 } 76 77 func getArgs(args []core.Value) (values.DateTime, values.Int, values.String, error) { 78 err := core.ValidateArgs(args, 3, 3) 79 if err != nil { 80 return emptyDateTime, emptyInt, emptyString, err 81 } 82 83 err = core.ValidateValueTypePairs( 84 core.NewPairValueType(args[0], types.DateTime), 85 core.NewPairValueType(args[1], types.Int), 86 core.NewPairValueType(args[2], types.String), 87 ) 88 if err != nil { 89 return emptyDateTime, emptyInt, emptyString, err 90 } 91 92 date := args[0].(values.DateTime) 93 amount := args[1].(values.Int) 94 unit := args[2].(values.String) 95 96 return date, amount, unit, nil 97 }