Date converter snippet

One way to do this is to have more than one action in the extension. This can be done by making the extension module-based and exporting more than one action. See example below.

Another way is to react to a modifier key – Option is the bets choice – by checking popclip.modifiers.option.

I’ll write up an example with everything in.

// #popclip
// name: DateFormatConverter
// icon: 📅
// description: Convert dates to a specified format.
// requirements: []
// language: javascript
// module: true

const dateOptions1 = { day: '2-digit', month: 'short', year: 'numeric' }; // "29 Jan 2024"
const dateOptions2 = { day: '2-digit', month: '2-digit', year: 'numeric' }; // "29/01/2024"

// Example function to convert date to the desired format
function convertDateToFormat(inputText, dateOptions) {
  // Attempt to parse the date using built-in Date parsing.
  // If no input text, use current date.
  const parsedDate = inputText.length > 0 ? new Date(inputText) : new Date();

  // Check if the date is valid
  if (!isNaN(parsedDate)) {
    return Intl.DateTimeFormat('en-GB', dateOptions).format(parsedDate);    
  } else {
    return "Invalid date format";
  }
}

// an action for each format
exports.actions = [{
  title: "DateFormat1",
  icon: "d1", // unimaginative icon for now
  code: () => popclip.pasteText(convertDateToFormat(popclip.input.text, dateOptions1))
},{
  title: "DateFormat2",
  icon: "d2",
  code: () => popclip.pasteText(convertDateToFormat(popclip.input.text, dateOptions2))
}];

Alternative using Option key to differentiate:

// ... rest as above

// choose format based on presence of option modifier.
// here we don't need to wrap the code in an object with title and icon,
// since we only have one action so we are happy to just inherit
// the extension's name and icon. (this is basically what happens under
// the hood when using a simple javascript action without `module: true`)
exports.action = () => {
  popclip.pasteText(convertDateToFormat(
    popclip.input.text,
    popclip.modifiers.option ? dateOptions2 : dateOptions1
  ));
}
1 Like