0

I have a batch file which creates a token file of name format xyz_yyyyddmmhhmmss (adding time stamp) based on some conditions. Issue is, if the token file is created from 0:00 to 9:59, the time part of the file name is of 5 digits and of 6 digits otherwise. It is required of it to remain of 6 digits.

    for /f "tokens=1 delims=/ " %%j in ("%date%") do set d1=%%j
    for /f "tokens=2 delims=/ " %%j in ("%date%") do set d2=%%j
    for /f "tokens=3 delims=/ " %%j in ("%date%") do set d3=%%j
    for /f "tokens=4 delims=/ " %%j in ("%date%") do set d4=%%j
    for /f "tokens=1 delims=: " %%j in ("%time%") do set t1=%%j
    for /f "tokens=2 delims=: " %%j in ("%time%") do set t2=%%j
    for /f "tokens=3 delims=:. " %%j in ("%time%") do set t3=%%j


    if exist %1xyz_*.tkn (del %1xyz_*.tkn 
    dir %1*.txt>%1xyz_%d4%%d2%%d3%%t1%%t2%%t3%.tkn)
    if not exist %xyz_*.tkn  (dir %1*.txt>%1xyz_%d4%%d2%%d3%%t1%%t2%%t3%.tkn)

Kindly give your inputs.

Thanks!

  • You should use `for /F "tokens=1-7 delims=/:., " %%I in ("%date%, %time%") do set "d1=%%I" & set "d2=%%J" & set "d3=%%K" & set "d4=%%L" & set "t1=%%M" & set "t2=%%N"` & set "t3=%%O"``; otherwise when running your code very very close to midnight and read `%date%`/%`time%` multiple times, you might get unexpected results; note that `%date%` and `%time%` return date and time in a format depending on your locale settings... – aschipfl May 03 '16 at 13:39
  • Whenever possible, you should prefer a solution, that is independent of local settings [like this](http://stackoverflow.com/a/18024049/2152082) – Stephan May 03 '16 at 14:02

1 Answers1

1

A long, long time ago, I found the basis somewhere of this (pretty sure not SO), made some modifications to it, and have cut-n-pasted it into virtually every batch file I've written since. I'm not sure I ever fully understood just how it works, but it does. You should be able to adapt it to your format without too much trouble.

  REM Creates a string in the form of YYYYMMDD-hhmm, with no embedded spaces
SET hh=%time:~0,2%
IF "%time:~0,1%"==" " SET hh=0%hh:~1,1%
SET DateString=%date:~10,4%%date:~4,2%%date:~7,2%-%hh%%time:~3,2%
Philip Kelley
  • 39,426
  • 11
  • 57
  • 92