This is an old revision of the document!

Formatting Timestamp in Batch File

While WinSCP is primarily an SFTP/FTP client, its powerful %TIMESTAMP% syntax can be used as a separate feature from a Windows batch file.

The %TIMESTAMP% syntax can be used as:

  • A locale-independent alternative to the date command/variable;1
  • An easy way to calculate relative times, like yesterday date, tomorrow date, time one hour ago, etc.

Advertisement

Locale-independent Timestamp Formatting

To use WinSCP to save formatted timestamp to an environment variable, use:

set TIMESTAMP_FORMAT=yyyy-mm-dd
for /F "tokens=* USEBACKQ" %%F in (`winscp.com /command "echo %%TIMESTAMP#%TIMESTAMP_FORMAT%%%" "exit"`) do set TIMESTAMP=%%F
echo %TIMESTAMP%

It outputs a current date in format 2016-09-29 on any locale.

Of course, if you actually just need to print the timestamp (or output it a file), you do not need to do it indirectly via the environment variable, just use a simple:

set TIMESTAMP_FORMAT=yyyy-mm-dd
winscp.com /command "echo %%TIMESTAMP#%TIMESTAMP_FORMAT%%%" "exit"

Calculating Relative Times

To calculate relative times, you can extend the batch file like below. The script will print the yesterday date.

set TIMESTAMP_FORMAT=yyyy-mm-dd
set TIMESTAMP_RELATIVE=-1D
for /F "tokens=* USEBACKQ" %%F in (`winscp.com /command "echo %%TIMESTAMP%TIMESTAMP_RELATIVE%#%TIMESTAMP_FORMAT%%%" "exit"`) do set TIMESTAMP=%%F
echo %TIMESTAMP%

Advertisement

Change the value of the TIMESTAMP_RELATIVE variable to +1D to calculate tomorrow date.

To calculate a time one hour ago, set the TIMESTAMP_RELATIVE to -1H and change the TIMESTAMP_FORMAT to include also a time a time, e.g. yyyy-mm-dd_hh:nn:ss.

More Options

For all options of the timestamp format and the relative date/time calculation, see the %TIMESTAMP% syntax documentation.

  1. The date command/variable uses locale-specific format, so common syntax like %date~...% yields expected yyyymmdd... value on US-locale only.Back

Last modified: by martin