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

     1  package datetime
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  
     7  	"github.com/MontFerret/ferret/pkg/runtime/core"
     8  	"github.com/MontFerret/ferret/pkg/runtime/values"
     9  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
    10  )
    11  
    12  // DATE parses a formatted string and returns DateTime object it represents.
    13  // @param {String} time - String representation of DateTime.
    14  // @param {String} [layout = "2006-01-02T15:04:05Z07:00"] - String layout.
    15  // @return {DateTime} - New DateTime object derived from timeString.
    16  func Date(_ context.Context, args ...core.Value) (core.Value, error) {
    17  	if err := core.ValidateArgs(args, 1, 2); err != nil {
    18  		return values.None, err
    19  	}
    20  
    21  	if err := core.ValidateType(args[0], types.String); err != nil {
    22  		return values.None, err
    23  	}
    24  
    25  	str := args[0].(values.String)
    26  	layout := values.DefaultTimeLayout
    27  
    28  	if len(args) > 1 {
    29  		if err := core.ValidateType(args[1], types.String); err != nil {
    30  			return values.None, err
    31  		}
    32  
    33  		layout = values.ToString(args[1]).String()
    34  	}
    35  
    36  	t, err := time.Parse(layout, str.String())
    37  
    38  	if err != nil {
    39  		return values.None, err
    40  	}
    41  
    42  	return values.NewDateTime(t), nil
    43  }