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.

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 (` /command "echo %%TIMESTAMP#%TIMESTAMP_FORMAT%%%" "exit"`) do set TIMESTAMP=%%F

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 a file), you do not need to do it indirectly via the environment variable, just use a simple:

set TIMESTAMP_FORMAT=yyyy-mm-dd /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
for /F "tokens=* USEBACKQ" %%F in (` /command "echo %%TIMESTAMP%TIMESTAMP_RELATIVE%#%TIMESTAMP_FORMAT%%%" "exit"`) do set TIMESTAMP=%%F

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.

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~...% yields expected yyyymmdd... value on US-locale only.
  script_formatting_timestamp_batch_file.txt · Last modified: by martin

Search Documentation

This page


About donations

$9   $19   $49   $99

About donations



Site design by Black Gate