Formatting Timestamp in Batch File

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

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.

Modify the TIMESTAMP_FORMAT as you need. For all options of the timestamp format, see the %TIMESTAMP% syntax documentation.

Of course, if you actually just need to print the timestamp (or output it to 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, e.g. yyyy-mm-dd_hh:nn:ss.

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

In PowerShell

In PowerShell, you can use its built-in timestamp functions.

To format the current timemestamp, use the Get-Date cmdlet and its -Format switch:

$timestamp = (Get-Date -Format "yyyy-MM-dd")
Write-Host $timestamp

To calculate relative times, use methods of the DateTime class, like the AddDays. To format the calculated timestamp, use the ToString method.

$yesterday = (Get-Date).AddDays(-1)
$timestamp = $yesterday.ToString("yyyy-MM-dd")
Write-Host $timestamp
  1. The date command/variable uses locale-specific format, so common syntax like %date:~10,4%%date:~4,2%%date:~7,2% yields expected yyyymmdd value on US-locale only.Back

Last modified: by martin