How do I use addHours in an expression?

I’m trying to use an expression that will add 12 hours to the current time. This isn’t working:
{{today = new Date().getTime()}}{{today.addHours(today.getTime(), 12)}}

This is: {{today = new Date().getTime()}}

Sorry, I’m really new to using n8n, and I’m not sure I get expressions.

This is for the start and end parameters for a Google Cal query.

Hi @Jason_Jason, have you had a look at our Date & Time node? It simplifies time calculations like adding 12 hours a lot like so:

Example Workflow
{
  "nodes": [
    {
      "parameters": {
        "action": "calculate",
        "value": "={{new Date()}}",
        "duration": 12,
        "timeUnit": "hours",
        "dataPropertyName": "in12hours",
        "options": {}
      },
      "name": "Date & Time",
      "type": "n8n-nodes-base.dateTime",
      "typeVersion": 1,
      "position": [
        450,
        300
      ]
    },
    {
      "parameters": {},
      "name": "Start",
      "type": "n8n-nodes-base.start",
      "typeVersion": 1,
      "position": [
        250,
        300
      ]
    },
    {
      "parameters": {
        "action": "calculate",
        "value": "={{new Date()}}",
        "duration": 12,
        "timeUnit": "hours",
        "dataPropertyName": "in12hours",
        "options": {}
      },
      "name": "Date & Time",
      "type": "n8n-nodes-base.dateTime",
      "typeVersion": 1,
      "position": [
        450,
        300
      ]
    }
  ],
  "connections": {
    "Start": {
      "main": [
        [
          {
            "node": "Date & Time",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}

If you want to use an expression only, this is vanilla Javascript not setting/reading variables and works fine in expressions: {{new Date(new Date().getTime() + (12 * 60 * 60 * 1000))}} (it just adds 12 * 60 * 60 * 1000 milliseconds to the current date/time, which is how Javascript stores dates - replace the 12 with any other amount of hours you might need).

image

1 Like

I think I want the expression only so it limits the number of objects returned from the Google Cal query.

I put that expression for the end date, and it returns an error. I think the format of the expression output is wrong (it’s not a date, it’s an object):

Sorry for that: To get a real date string instead of a date object, you could append .toISOString() like so: {{new Date(new Date().getTime() + (12 * 60 * 60 * 1000)).toISOString()}}. This would also work for the start time (which seems to be an epoch number).

Assuming your start date is “now”, that could be an expression like {{new Date().toISOString()}}.

1 Like

I do the same thing with the date and time node, I always feel that if I have to use JavaScript in a workflow I have failed :joy:

We set the from and to time formats in date and time nodes then use the result of that in the Google cal node.

2 Likes

Thank you both!

2 Likes