amazon-web-servicesaws-api-gatewayvelocity

How can I create a current ISO8601 timestamp in AWS Api Gateway Mapping Template (Velocity, VTL)?


In AWS Api Gateway Mapping Template the context variable gives access to the UNIX epoch timestamp:

$context.requestTimeEpoch

But how can I generate a ISO8601 formatted timestamp like 2018-02-06T19:01:35.749Z?

AWS AppSync provides Time helpers in $util.time that does exactly what I want:

$util.time.nowISO8601()

But this helper is not available in API Gateway.


Solution

  • Unfortunately it is limited to certain variables and operations. The post below provides a way to remap the part from $context.requestTime

    Map the context.requestTimeEpoch to a custom date format string in AWS API Gateway mapping template

    Here's a remap into $isoDate that may work for your case

    ## context.RequestTime, split the string for date
    #set($all_parts = $context.requestTime.split(':'))
    
    ## Break out date part into day/month/year
    #set($date_parts = $all_parts[0].split('/'))
    #set($day = $date_parts[0])
    #set($month_name = $date_parts[1])
    #set($year = $date_parts[2])
    
    ## Set an array to convert month names to month numbers
    #set($months = {'Jan':'01', 'Feb':'02', 'Mar':'03', 'Apr':'04', 'May':'05', 'Jun':'06', 'Jul':'07', 'Aug':'08', 'Sep':'09', 'Oct':'10', 'Nov':'11', 'Dec':'12'})
    #set($month = $months.get($month_name))
    
    ## Break up the time part into hours/mins/seconds
    #set($hours = $all_parts[1])
    #set($minutes = $all_parts[2])
    #set($seconds = $all_parts[3].split(' ')[0])
    
    ## Get milliseconds from timestamp (last 3 digits)
    #set($timestamp = $context.requestTimeEpoch)
    #set($milliseconds = $timestamp % 1000)
    #set($time = "${hours}:${minutes}:${seconds}.${milliseconds}")
    
    ## Update the path to use the new variables
    #set($isoDate = "${year}-${month}-${day}T${time}Z")