github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/datetime/compare.go (about)

     1  package datetime
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/pkg/errors"
     7  
     8  	"github.com/MontFerret/ferret/pkg/runtime/core"
     9  	"github.com/MontFerret/ferret/pkg/runtime/values"
    10  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
    11  )
    12  
    13  // DATE_COMPARE checks if two partial dates match.
    14  // @param {DateTime} date1 - First date.
    15  // @param {DateTime} date2 - Second date.
    16  // @param {String} unitRangeStart - Unit to start from.
    17  // @param {String} [unitRangeEnd="millisecond"] - Unit to end with. Error will be returned if unitRangeStart unit less that unitRangeEnd.
    18  // @return {Boolean} - True if the dates match, else false.
    19  func DateCompare(_ context.Context, args ...core.Value) (core.Value, error) {
    20  	err := core.ValidateArgs(args, 3, 4)
    21  	if err != nil {
    22  		return values.None, err
    23  	}
    24  
    25  	err = core.ValidateValueTypePairs(
    26  		core.NewPairValueType(args[0], types.DateTime),
    27  		core.NewPairValueType(args[1], types.DateTime),
    28  		core.NewPairValueType(args[2], types.String),
    29  	)
    30  	if err != nil {
    31  		return values.None, err
    32  	}
    33  
    34  	date1 := args[0].(values.DateTime)
    35  	date2 := args[1].(values.DateTime)
    36  	rangeStart := args[2].(values.String)
    37  	rangeEnd := values.NewString("millisecond")
    38  
    39  	if len(args) == 4 {
    40  		err = core.ValidateType(args[3], types.String)
    41  
    42  		if err != nil {
    43  			return values.None, err
    44  		}
    45  
    46  		rangeEnd = args[3].(values.String)
    47  	}
    48  
    49  	unitStart, err := UnitFromString(rangeStart.String())
    50  	if err != nil {
    51  		return values.None, err
    52  	}
    53  
    54  	unitEnd, err := UnitFromString(rangeEnd.String())
    55  	if err != nil {
    56  		return values.None, err
    57  	}
    58  
    59  	if unitStart < unitEnd {
    60  		return values.None, errors.Errorf("start unit less that end unit")
    61  	}
    62  
    63  	for u := unitEnd; u <= unitStart; u++ {
    64  		if IsDatesEqual(date1.Time, date2.Time, u) {
    65  			return values.NewBoolean(true), nil
    66  		}
    67  	}
    68  
    69  	return values.NewBoolean(false), nil
    70  }