How to get a UNIVERSAL Windows batch file timestamp

前端 未结 5 1676
独厮守ぢ
独厮守ぢ 2021-01-12 03:45

I\'m having trouble generating a timestamp in a Windows batch file, because I get diferent date formats on different Windows versions.

My machine:

&g         


        
5条回答
  •  北恋
    北恋 (楼主)
    2021-01-12 04:25

    Check out doff.exe. I use this a lot for getting timestamps for naming log files. From its web site:

    DOFF prints a formatted date and time, with an optional date offset, (e.g -1 prints yesterday's date, +1 prints tomorrow's date). To view all the options available, execute "doff -h". I typically use this utility for renaming log files so that they include a timestamp, (see the third example below). This code should compile under Unix/Linux, as well as DOS.

    Sample commands:

    C:\>doff
    19991108131135
    

    With no parameters the output is the current date/time in the following format: yyyymmddhhmiss

    C:\>doff mm/dd/yyyy
    11/08/1999
    

    In the above example a date format specification is given.

    @echo off
    for /f "tokens=1-3 delims=/ " %%a in ('doff mm/dd/yyyy -1') do (
    set mm=%%a
    set dd=%%b
    set yyyy=%%c)
    rename httpd-access.log httpd-access-%yyyy%%mm%%dd%.log
    

    The sample batch file above shows a neat way to rename a log file based on yesterday's date. The "for" command executes doff to print yesterday's date, (the "-1" parameter specifies yesterday), then extracts each component of the date into DOS batch file variables. The "rename" command renames "httpd-access.log" to "httpd-access-[yesterday's date].log"


    Also check out Microsoft's now.exe, available in the Windows Server 2003 Resource Kit Tools. One bad thing I found out (the hard way) about it is it sets the ERRORLEVEL to the number of characters printed.

    Looks like this:

    c:\>now
    
    Thu May 19 14:26:45 2011
    

    Help:

    NOW   :  Display Message with Current Date and Time
    
    Usage : NOW [message to be printed with time-stamp]
    
        NOW displays the current time, followed by its command-line arguments.
        NOW is similar to the standard ECHO command, but with a time-stamp.
    

提交回复
热议问题