4

I need to use date /t command and convert the date format to DD-MM-YYYY_weekday with all the "-" and "_" as listed I can't find an answer on my question. Could you please help me?

3 Answers3

4

I would like to have it formatted like DD-MM-YYYY_weekday

Below are two solutions:

  • Batch file
  • PowerShell (a simple one line solution)

The Batch file solution

First, what not to do:

  • Using %date% to provide a solution is, as used in the other answers, dependent on the OS Locale, Regional, and Language settings and may provide wrong or missing information.

  • For example, the short date format on my PC does not output the weekday at all.

The right way to solve the problem:

  • Using wmic, on the other hand, works independently of OS Locale, Language or the user's chosen date format (Control Panel/Regional).

The following batch file uses wmic to retrieve the date and (local) time, so doesn't suffer the disadvantage of a solution using %date%.

The batch file also calls PowerShell to retrieve the weekday, as that is not directly available otherwise.

getdate.cmd:

@echo off
setlocal
rem get the date
rem use findstr to strip blank lines from wmic output
for /f "usebackq skip=1 tokens=1-3" %%g in (`wmic Path Win32_LocalTime Get Day^,Month^,Year ^| findstr /r /v "^$"`) do (
  set _day=00%%g
  set _month=00%%h
  set _year=%%i
  )
rem pad day and month with leading zeros
set _month=%_month:~-2%
set _day=%_day:~-2%
rem get day of the week
for /f %%k in ('powershell ^(get-date^).DayOfWeek') do (
  set _dow=%%k
  )
rem output format required is DD-MM-YYYY_weekday
echo %_day%-%_month%-%_year%_%_dow%
endlocal

Example output:

F:\test>getdate
06-06-2016_Monday

Credits:


Alternative Powershell solution.

A simple one line PowerShell solution is:

Get-Date -format "yyyy-MM-dd_dddd"

Example output:

PS F:\test> Get-Date -format "yyyy-MM-dd_dddd"
2016-06-06_Monday

Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • for /f - Loop command against the results of another command.
  • getdate - Display the date and time independent of OS Locale, Language or the users chosen date format (Control Panel/Regional).
  • variables - Extract part of a variable (substring).
  • wmic - Windows Management Instrumentation Command.
DavidPostill
  • 156,873
2

Try:

echo %date:~7,2%-%date:~4,2%-%date:~10,4%_%date:~0,3%

Source for manipulation tips

Jedi
  • 860
1

This should do it. It uses the for command to tear apart the date /t results and uses echo to construct the output. The details can be worked out at the command-line.

for /f "tokens=1,2,3,4 delims=/ " %a in ('date /t') do echo %b-%c-%d_%a

uSlackr
  • 8,995