Rudy is me

A weblog (mostly) about PHP and TYPO3 development

Shortcut to get the current Unix timestamp in PhpStorm

Because it's convention to use the current timestamp as the code for any Exception thrown in TYPO3, I need the current timestamp regularly when making or altering a TYPO3 extension. I used to go to a site like to get the current timestamp, but it is possible to create a shortcut to get the current timestamp in PhpStorm using Live Templates.

To create this Live Template in PhpStorm, go to File > Settings (or Ctrl+Alt+S). You can find Live Templates under Editor. Click on the Plus icon next to the list of available templates and select Live Template. You can now fill in the fields below list to create the new template with the following data:

  • Abbreviation: timestamp
    This will be the text you type in your code to get the timestamp.
  • Description: Current Unix timestamp
    This is just a description.
  • Template text: $timestamp$
    This is the text of the template. In this case it's only a variable which will be replaced with the current Unix timestamp.

Now click on the Edit variables button. Here we can set a calculated or default value for all variables in the template. In this case you should only see the timestamp variable here. Click on the field below Expression to set the function to calculate the current timestamp. The functions you can use are documented here. There is a timestamp() function, but this gives the time in miliseconds since 1 january 1970 and Unix timestamp is in seconds. To get the Unix timestamp you will need the following expression:

groovyScript("(int) (new Date().getTime() / 1000L);")

This will execute a bit of Groovy Script. It will create a current Date object, get the timestamp (in miliseconds) and divide that by 1000 to get the timestamp in seconds.

Check the "Skip if defined" checkbox at the end and click Ok to save the variable. Finally, you have to define for which types of files you want the Live Template to be available. In this case we want it available for all, so click "Define" at the bottom and check the "Everywhere" checkbox. Click "Apply" to save or "Ok" to save and close the Settings window.

You can now type "timestamp" to get the current Unix timestamp in any file you edit in PhpStorm.

If you want to learn more about Live Template (and you should, they are very handy), check out the documentation.