Create a Snippet or Shortcut in VS Code to Insert the Current Date & Time

When I write blog articles, one thing I always need to enter is the current date and time or future date and time if I want to publish later. I often copy and paste a previous article, then adjust all the properties. But it would be nice if I could use a snippet or keyboard shortcut to enter the date and time for me.

It turns out you can! VS Code has variables available to use for snippets!

You can create a snippet for Markdown files in VS Code by opening up the snippets JSON file. The easiest way is as follows:

  • Open the Command Palette with Ctrl+Shift+p
  • Select "Preferences: Configure User Snippets"
  • Select "markdown.json"

Add your snippet here! Below is an example of mine for the CDT timezone, which is 5 hours behind UTC.

    "Current Date": {
        "prefix": "date",
        "body": [
            "$CURRENT_YEAR-$CURRENT_MONTH-${CURRENT_DATE}T$CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND.000-05:00"
        ],
        "description": "Add Current date & time"
    }

Now I can type date and hit tab or use the ctrl+space shortcut followed by date and the enter key to insert the current date and time in this format: 2020-08-01T10:14:04.000-05:00

One important part is the dollar sign and curly braces around CURRENT_DATE. VS Code can determine all the other variables apart because they're followed by a non-alphanumeric character. I have a "T" following that variable. To help VS Code separate an alphabetical character following a variable, we wrap the variable in the dollar sign and curly brace.

If you would rather have a keyboard shortcut you can open up the keybindings.json file in VS Code.

  • Open the Command Palette with Ctrl+Shift+p
  • Select "Preferences: Open Keyboard Shortcuts (JSON)"

Then insert your own modified version of the keybinding below.

    {
        "key": "ctrl+d t",
        "command": "editor.action.insertSnippet",
        "when": "editorTextFocus",
        "args": {
            "snippet": "$CURRENT_YEAR-$CURRENT_MONTH-${CURRENT_DATE}T$CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND.000-05:00"
        }
    }

In my example pressing ctrl+d and than letting go and pressing the t button would insert my current date and time.

One Last Thing...

If you have a question or see a mistake, please comment below.

If you found this post helpful, please share it with others. It's the best thanks I can ask for & it gives me momentum to keep writing!

Matt Ferderer
Software Developer focused on making great user experiences. I enjoy learning, sharing & helping others make amazing things.
Let's Connect