1

If I run a script, timestamp.cmd, with code below, on the command line on Windows 7 (cmd.exe):

@echo off
echo generating timestamp file >>timestamp.txt
for /f "tokens=1-3 delims=/ " %%a in ('date /t') do (set mydate=%%a%%b%%c)
for /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate% > timestamp.txt
echo %mytime%00 >> timestamp.txt

Then I get output:

31012017 
084300

But if I run it as a command from a service then the output is:

Tue0131 
0941 AM00

Firstly, I don't understand why I would get such output. And secondly, how do I fix it?

Angus Comber
  • 9,316
  • 14
  • 59
  • 107
  • Formatting of date and time values is a configurable item, Control Panel > Language applet. But such formatting applies only to your user account, and it looks like you changed it, the service probably runs with the Service account. Consider running the service with another account. Or writing a program that outputs the way you like it, a programmer's solution. – Hans Passant Jan 31 '17 at 09:00

1 Answers1

3

Why?

Date/time formats are bound to user configuration. Each user account in the same system can have different configurations. Your account and the account of the system service don't have the same configuration.

How?

Use a different method to retrieve the date, select a source that consistently gives a date/time format in a known format.

Using robocopy

@echo off
    setlocal enableextensions disabledelayedexpansion

    set "myDate="
    for /f "tokens=1-6 delims=:/ " %%a in ('
        robocopy "|" . /njh
    ') do if not defined myDate (
        set "myDate=%%c%%b%%a"
        set "myTime=%%d%%e%%f"
    )

    >"timestamp.txt" (
        echo %myDate%
        echo %myTime%
    )

Using wmic

@echo off
    setlocal enableextensions disabledelayedexpansion

    for /f "tokens=2 delims==." %%a in ('
        wmic os get localdatetime /format:list
    ') do set "myDate=%%a"

    set "myTime=%myDate:~-6%"
    set "myDate=%myDate:~6,2%%myDate:~4,2%%myDate:~0,4%"

    >"timestamp.txt" (
        echo %myDate%
        echo %myTime%
    )

Or ...

You should take a look at this answer and select the method that better suits your needs.

Community
  • 1
  • 1
MC ND
  • 69,615
  • 8
  • 84
  • 126
  • Nice way of writing `FOR` loops over command output, with the command on a separate line! – zb226 Jan 31 '17 at 10:00