Skip to content

Instantly share code, notes, and snippets.

@NorskNoobing
Created December 22, 2022 03:24
Show Gist options
  • Save NorskNoobing/ef059c2af90301dd92e025cf79339be9 to your computer and use it in GitHub Desktop.
Save NorskNoobing/ef059c2af90301dd92e025cf79339be9 to your computer and use it in GitHub Desktop.

Get a specific date with and offset relative to the input

Installation

  1. Copy the source code that you can find below to a file named getDate.js, and save it in the folder that you'll use for templater userscripts e.g. Obsidian/Templater/Scripts/getDate.js
  2. Go to Settings -> Templater -> User Script Functions -> Script files folder location and set it to your script folder e.g. Obsidian/Templater/Scripts, then press the Refresh button.

Usage

You can use the following syntax to call the function:

<%tp.user.getDate(INPUT_DATE,YEAROFFSET,MONTHOFFSET,DAYOFFSET)%>

This would work with both positive and negative integer values as parameters.

Example 1

Input

<%tp.user.getDate("2020-12-22",0,0,1)%>

Output

2020-12-23

Example 2

Here I'm creating a daily notes file for a previous date. The name of the note file would then be 2022-12-01.

Input

Note that I pass the tp.file.title function as a parameter to the getDate() function.

<%tp.user.getDate(tp.file.title,0,0,1)%>

Output

2022-12-02

Code

function getDate(title,yearOffset = 0, monthOffset = 0, dayOffset = 0) {
    const d = new Date(title)
    let day = d.getDate()
    let month = d.getMonth() + 1
    let year = d.getFullYear()

    day = day + dayOffset
    month = month + monthOffset
    year = year + yearOffset

    day = ("0" + day).slice(-2)
    month = ("0" + month).slice(-2)

    return year + "-" + month + "-" + day
}
module.exports = getDate;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment