2

Am trying to format date in cmd windows but it is not coming out nicely.

echo %date% +"%d-%B-%Y". How should I go about it?

Moses
  • 143

2 Answers2

2

You might be interested in the wmic command which can return the local date/time in a locale-independent manner.


@echo off
Title wmic command which can return the local date/time in a locale-independent manner
@for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x
set today=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%
echo Today : %today%
set "year=%MyDate:~2,2%"
set "month=%MyDate:~4,2%"
set "day=%MyDate:~6,2%"
echo %day%-%month%-%year%
pause
Hackoo
  • 1,404
-1

I belive this is what you want:

set year=%date:~10,4%
set month=%date:~4,2%
set day=%date:~7,2%
set dateformatted=%month%-%day%-%year%
echo %dateformatted%

Answer from here. Have fun!

  • This prints 9--1--021 on my pc. (Note that %date% is culture specific) – Berend Nov 19 '21 at 12:15
  • Wouldn't chopping up wmic os get LocalDateTime be a better (locale independent) solution? – Richard Nov 19 '21 at 12:25
  • @Richard Absolutely. That link contains several answers (of which %date% is the worst, IMO), including wmic. – Berend Nov 19 '21 at 12:27
  • @Berend Hah, serves me right for not looking at the contents of the link! The biggest issue I can see is the requirement for %B which will require matching a number to the full name of the month. – Richard Nov 19 '21 at 12:31
  • Idk why but wmic gives some whacky numbers instead of a date on my computer. There is the answer's URL if it didn't work for you guys. I guess it changes from area to area. – TheCodeExpert Nov 19 '21 at 12:52
  • @TheCodeExpert Odd, mine gives 20211119131755.595000+000 which looks to be yyyymmddhhmmss. I have no idea what is after the . - I'm guessing sub-seconds but it's hard to tell because it takes a second for Windows to return the value. – Richard Nov 19 '21 at 13:20
  • @Richard I'm getting your result when I run wmic. I guess it really depends on something – TheCodeExpert Nov 19 '21 at 13:41