getTimestamp.bat for time and date processing

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Message
Author
foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: getTimestamp.bat for time and date processing

#31 Post by foxidrive » 27 Nov 2015 23:24

dbenham wrote:I've been pretty much off the grid for a few months, concentrating on work and music.


Do you play music Dave, or is listening your primary enjoyment?

I was a musician - played guitar and sang with others. Taught myself keyboard, played recorder as a kid, fiddled with a mouth organ and accordion.
All good fun!


Thanks for the gettimestamp update...

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: getTimestamp.bat for time and date processing

#32 Post by dbenham » 28 Nov 2015 09:05

[OffTopic]
I used to sing a lot with various choral groups, the most satisfying being the Baltimore Choral Arts Society, and the Baltimore Symphony Chorus. But I've pretty much given up singing for the moment.

For the past 6 years I have been playing Native American flutes, mostly at open mics. It's all improvisation. I especially like to jam with one or more additional musicians. A slow week I may play only once. But recently I've been active as much as 5 nights in one week.

I have a bunch of music posted to the internet:
The host of my favorite open mic has posted a handful of my performances within his "Favorite Open Mic moments" playlist
I've got 40+ videos I've posted myself on my YouTube channel
And I have over 3+ hours of music posted on my SoundCloud page at http://soundcloud.com/dave-benham
There are additional videos others have posted of me out there somewhere.
[/OffTopic]


Dave Benham
Last edited by dbenham on 03 Dec 2015 06:50, edited 1 time in total.

Squashman
Expert
Posts: 4484
Joined: 23 Dec 2011 13:59

Re: getTimestamp.bat for time and date processing

#33 Post by Squashman » 28 Nov 2015 16:06

My oldest son is on year 8 singing with the Green Bay Boy Choir and my youngest joined this year as well. They went to sing in Austria and the Czech Republic last year.

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: getTimestamp.bat for time and date processing

#34 Post by foxidrive » 03 Dec 2015 03:08

dbenham wrote:[OffTopic]
I used to sing a lot with various choral groups, the most satisfying being the Baltimore Choral Arts Society, and the Baltimore Symphony Chorus. But I've pretty much given up singing for the moment.

For the past 6 years I have been playing Native American flutes, mostly at open mics. It's all improvisation. recently I've been active as much as 5 nights in one week.
[/OffTopic]


I love the gentle sound of the flute Dave. You and your companions make lovely music.

Squashman wrote:My oldest son is on year 8 singing with the Green Bay Boy Choir and my youngest joined this year as well. They went to sing in Austria and the Czech Republic last year.


That can only be a great experience for them Squashman. Making music is a highlight in my life, and I'm sure they will treasure it into the future too.

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: getTimestamp.bat for time and date processing

#35 Post by dbenham » 01 Apr 2016 11:59

MCP wrote:This original post is at viewtopic.php?p=45979#p45979

Foxidrive,
Thanks for the link. I'm sure someone could probably use that script to code part of what I'm trying to accomplish but for me it is beyond my current experience level to understand it and then write the additional code required to use it in the way I need in any kind of timely manner.

I'm really looking for something a bit more "turn key" that I can just copy and plug-in to my batch file. If you have any additional examples that are a little closer to my requirements or can put together something that specifically targets what I need then that would be fantastic.

Mike

It doesn't get much more turnkey than getTimestamp.bat.

You need to know the date and time format used by your locale. For me I need mm-dd-yyyy and hh:mm:ss.ff, where hh is in 24 hour format, and .ff is optional fractional seconds. Also, you must be running as administrator if you want to modify your computer's system date/time.

Code: Select all

for /f "tokens=1,2" %%A in (
  'gettimestamp /oh -3 /f "{mm}-{dd}-{yyyy} {hh}:{nn}:{ss}"'
) do date %%A & time %%B


Dave Benham

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: getTimestamp.bat for time and date processing

#36 Post by foxidrive » 08 Jul 2016 19:06

Dave, I have a task to add these times one-by-one and get a cumulative result from each step, but also adding the day in a 2 digit zero padded figure.

Can you give me a clue please?

Code: Select all

00:00:00:000
01:25:56.606
01:29:11.410
01:30:35.314
01:28:31.956
00:46:53.378
01:30:01.046
01:30:21.032
01:32:05.801
01:30:50.729
01:30:44.546
01:31:11.407
01:29:52.438
00:47:12.321
01:40:47.929
01:29:07.127
00:47:58.977
01:31:00.337
01:31:01.505
01:29:55.248
01:32:21.105

ShadowThief
Expert
Posts: 1166
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: getTimestamp.bat for time and date processing

#37 Post by ShadowThief » 08 Jul 2016 20:03

Couldn't you just convert the entire timestamp to seconds and do math that way?

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: getTimestamp.bat for time and date processing

#38 Post by foxidrive » 09 Jul 2016 05:01

That's the hard bit for me. I have panic attacks when I have to add 3 cents and 4 cents at the supermarket.

It would need to be done in milliseconds and I don't understand all the complexity in gettimestamp.bat
Maybe jeval.bat would be better but my brain is still not up to the task.

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: getTimestamp.bat for time and date processing

#39 Post by dbenham » 09 Jul 2016 14:00

This post is for releasing getTimestamp version 2.5

I discovered a significant bug with version 2.4 when doing date/time offset computations where the local timezone of the original value is different than the local timezone of the result due to daylight savings issues.

Here is a simple loop that demonstrates the 2.4 bug

Code: Select all

C:\test>for /l %M in (0 1 12) do @getTimestamp -d "'1/1/2016 UTC'" -od %M*30 -u
2016-01-01T00:00:00.000+00:00
2016-01-31T00:00:00.000+00:00
2016-03-01T00:00:00.000+00:00
2016-03-30T23:00:00.000+00:00
2016-04-29T23:00:00.000+00:00
2016-05-29T23:00:00.000+00:00
2016-06-28T23:00:00.000+00:00
2016-07-28T23:00:00.000+00:00
2016-08-27T23:00:00.000+00:00
2016-09-26T23:00:00.000+00:00
2016-10-26T23:00:00.000+00:00
2016-11-26T00:00:00.000+00:00
2016-12-26T00:00:00.000+00:00
My base timestamp is midnight, Jan 1, 2016 UTC, and I add multiples of 30 days. My local time zone is the U.S. Eastern Time, which follows daylight savings. The time should remain midnight throughout. But notice how the daylight savings months are off by an hour :!: :(

The fix was quite simple. I just had to make sure I always use the UTC functions whenever I perform date computations

So here is the correct result using version 2.5:

Code: Select all

C:\test>for /l %M in (0 1 12) do @getTimestamp -d "'1/1/2016 UTC'" -od %M*30 -u
2016-01-01T00:00:00.000+00:00
2016-01-31T00:00:00.000+00:00
2016-03-01T00:00:00.000+00:00
2016-03-31T00:00:00.000+00:00
2016-04-30T00:00:00.000+00:00
2016-05-30T00:00:00.000+00:00
2016-06-29T00:00:00.000+00:00
2016-07-29T00:00:00.000+00:00
2016-08-28T00:00:00.000+00:00
2016-09-27T00:00:00.000+00:00
2016-10-27T00:00:00.000+00:00
2016-11-26T00:00:00.000+00:00
2016-12-26T00:00:00.000+00:00


And here is getTimestamp version 2.5

Code: Select all

@if (@X)==(@Y) @end  /* harmless hybrid line that begins a JScript comment
@goto :batch
::
::getTimestamp.bat version 2.5 by Dave Benham
::
::  Release History:
::    2.5 2016-07-09 - Fixed bug with offset computations when the before and
::                     after have different time zones due to daylight savings.
::    2.4 2015-11-27 - Added formats to support comma as decimal mark in
::                     ISO 8601 time and timestamp formats.
::                     Added formats to support ISO 8601 week dates
::                     and ordinal dates.
::                     Rearranged documentation, and added examples for
::                     base date specified as a list of numeric values.
::    2.3 2015-07-11 - Added {ISO-xx}, {ISOxx}, {DY} and {DDY} formats
::                     Added -?? (paged help) option
::                     Allow user defined default option values by defining
::                     variables of the form "GetTimestamp-OPTION=VALUE"
::    2.2 2014-12-03 - Doc fix: -R ReturnVariable is unchanged if err occurs
::    2.1 2014-12-03 - Added GOTO at top to increase performance (32% faster)
::    2.0 2014-12-02 - Major rewrite: most code now in JScript (25% faster)
::                     Better error handling
::                     May now use /Option or -Option
::                     Added -V option
::                     Added {{} format value to enable unambiguous { literal
::    1.1 ????-??-?? - Added -Z option and obscure bug fixes
::    1.0 2013-07-17 - Initial release
::
::============ Documentation ===========
:::
:::getTimestamp  [-option [value]]...
:::
:::  Displays a formatted timestamp. Defaults to the current local date
:::  and time using an ISO 8601 format with milliseconds, time zone
:::  and punctuation, using period as a decimal mark.
:::
:::  Returned ERRORLEVEL is 0 upon success, 1 if failure.
:::
:::  Options may be prefaced with - or /
:::
:::  All options have default values. The default value can be overridden by
:::  defining an evironment variable of the form "GetTimestamp-OPTION=VALUE".
:::  For example, upper case English weekday abbreviations can be specified as
:::  the default by defining "GetTimestamp-WKD=SUN MON TUE WED THU FRI SAT".
:::
:::  Command line option values take precedence, followed by environment variable
:::  defaults, followed by built in defaults.
:::
:::  The following options are all case insensitive:
:::
:::    -?  : Prints this documentation for getTimestamp
:::
:::    -?? : Prints this documentation with pagination via MORE
:::
:::    -V  : Prints the version of getTimeStamp
:::
:::    -D DateSpec
:::
:::       Specify the base date and time.
:::       Default value is current local date and time.
:::       The DateSpec supports many formats:
:::
:::         ""    (no value)
:::
:::           Current date and time - the default
:::
:::         milliseconds
:::
:::           A JScript numeric expression that represents the number of
:::           milliseconds since 1970-01-01 00:00:00 UTC.
:::           Decimal values are truncated.
:::           Negative values represent dates prior to 1970-01-01.
:::
:::         "'Date [Time] [TimeZone]'"
:::
:::           A string representation of the date and time. The date information
:::           is required, the time and time zone are optional. Missing time info
:::           is assumed to be 0 (midnight). Missing time zone info is assumed to
:::           be local time zone.
:::
:::           The Date, Time, and TimeZone information can be represented as any
:::           string that is accepted by the JScript Date.Parse() method.
:::           There are many formatting options. Documentation is available at:
:::           http://msdn.microsoft.com/en-us/library/k4w173wk(v=vs.84).aspx
:::
:::           Examples of equivalent representations of Midnight on January 4,
:::           2013 assuming local time zone is U.S Eastern Standard Time (EST):
:::
:::             '1-4-2013'                    Defaults to local time zone
:::             "'January 4, 2013 EST'"       Explicit Eastern Std Time (US)
:::             "'2013/1/4 -05'"              Explicit Eastern Std Time (US)
:::             "'Jan 3 2013 23: CST'"        Central Standard Time (US)
:::             "'2013 3 Jan 9:00 pm -0800'"  Pacific Standard Time (US)
:::             "'01/04/2013 05:00:00 UTC'"   Universal Coordinated Time
:::             "'1/4/2013 05:30 +0530'"      India Standard Time
:::
:::         "year, month[, day[, hour[, minute[, second[, millisecond]]]]]"
:::
:::           A comma delimited list of numeric JScript expressions representing
:::           various components of date and time. Year and month are required,
:::           the rest are optional. Missing values are treated as 0.
:::           Decimal values are truncated. A 0 month represents January.
:::           A 1 day represents the first day of the month. A 0 day represents
:::           the last day of the prior month. The date/time value is always
:::           in local time. There is no mechanism to specify a time zone.
:::
:::           Examples: (all in local time)
:::             "2012,0,1,12,45,3,121"  12:45:03.121 on Jan 1, 2012
:::             "2012,0,1,12"           Noon on Jan 1, 2012
:::             "2012,1,1"              Midnight on Feb 1, 2012
:::             "2012,2,0"              Midnight on Feb 29, 2012 (last day of Feb)
:::             "2012,2"                Midnight on Feb 29, 2012 (last day of Feb)
:::
:::           The ability to use JScript expressions makes it convenient to do
:::           date and time offset computations in a very compact form.
:::
:::           For example, starting with:
:::             "2015,8,7,14,5"        Sep 7, 2015 at 14:05:00
:::
:::           It is simple to subtract 30 days and 30 minutes from the above:
:::             "2015,8,7-30,14,5-30"  Aug 8, 2015 at 13:35:00
:::
:::    -U  : Returns a UTC timestamp instead of local timestamp.
:::          Default is a local timestamp.
:::
:::    -Z TimeZoneMinuteOffset
:::
:::       Returns the timestamp using the specified time zone offset.
:::       TimeZoneMinuteOffset is a JScript numeric expression that
:::       represents the number of minutes offset from UTC.
:::       Decimal values are truncated.
:::       Default is empty, meaning local timezone.
:::
:::    -OY YearOffset
:::
:::       Specify the number of years to offset the base date/time.
:::       The JScript numeric expression is truncated to an integral number.
:::       Default is 0
:::
:::    -OM MonthOffset
:::
:::       Specify the number of months to offset the base date/time.
:::       The JScript numeric expression is truncated to an integral number.
:::       Default is 0
:::
:::    -OD DayOffset
:::
:::       Specify the number of days to offset the base date/time.
:::       The JScript numeric expression is truncated to an integral number.
:::       Default is 0
:::
:::    -OH HourOffset
:::
:::       Specify the number of hours to offset the base date/time.
:::       The JScript numeric expression is truncated to an integral number.
:::       Default is 0
:::
:::    -ON MinuteOffset
:::
:::       Specify the number of minutes to offset the base date/time.
:::       The JScript numeric expression is truncated to an integral number.
:::       Default is 0
:::
:::    -OS SecondOffset
:::
:::       Specify the number of seconds to offset the base date/time.
:::       The JScript numeric expression is truncated to an integral number.
:::       Default is 0
:::
:::    -OF MillisecondOffset
:::
:::       Specify the number of milliseconds to offset the base date/time.
:::       The JScript numeric expression is truncated to an integral number.
:::       Default is 0
:::
:::    -F FormatString
:::
:::       Specify the timestamp format.
:::       Default is "{ISO-TS.}"
:::       Strings within braces are dynamic components.
:::       All other strings are literals.
:::       Available components (case insensitive) are:
:::
:::         {YYYY}  4 digit year, zero padded
:::
:::         {YY}    2 digit year, zero padded
:::
:::         {Y}     year without zero padding
:::
:::         {MONTH} month name, as preferentially specified by:
:::                    1) -MONTH option
:::                    2) GetTimestamp-MONTH environment variable
:::                    3) Mixed case, English month names
:::
:::         {MTH}   month abbreviation, as preferentially specified by:
:::                    1) -MTH option
:::                    2) GetTimestamp-MTH environment variable
:::                    3) Mixed case, English month abbreviations
:::
:::         {MM}    2 digit month number, zero padded
:::
:::         {M}     month number without zero padding
:::
:::         {WEEKDAY} day of week name, as preferentially specified by:
:::                    1) -WEEKDAY option
:::                    2) GetTimestamp-WEEKDAY environment variable
:::                    3) Mixed case, English day names
:::
:::         {WKD}   day of week abbreviation, as preferentially specified by:
:::                    1) -WKD option
:::                    2) GetTimestamp-WKD environment variable
:::                    3) Mixed case, English day abbreviations
:::
:::         {W}     day of week number: 0=Sunday, 6=Saturday
:::
:::         {DD}    2 digit day of month number, zero padded
:::
:::         {D}     day of month number, without zero padding
:::
:::         {DDY}   3 digit day of year number, zero padded
:::
:::         {DY}    day of year number, without zero padding
:::
:::         {HH}    2 digit hours, 24 hour format, zero padded
:::
:::         {H}     hours, 24 hour format without zero padding
:::
:::         {HH12}  2 digit hours, 12 hour format, zero padded
:::
:::         {H12}   hours, 12 hour format without zero padding
:::
:::         {NN}    2 digit minutes, zero padded
:::
:::         {N}     minutes without padding
:::
:::         {SS}    2 digit seconds, zero padded
:::
:::         {S}     seconds without padding
:::
:::         {FFF}   3 digit milliseconds, zero padded
:::
:::         {F}     milliseconds without padding
:::
:::         {AM}    AM or PM in upper case
:::
:::         {PM}    am or pm in lower case
:::
:::         {ZZZZ}  timezone expressed as minutes offset from UTC,
:::                 zero padded to 3 digits with sign
:::
:::         {Z}     timzone expressed as minutes offset from UTC without padding
:::
:::         {ZS}    ISO 8601 timezone sign
:::
:::         {ZH}    ISO 8601 timezone hours (no sign)
:::
:::         {ZM}    ISO 8601 timezone minutes (no sign)
:::
:::         {TZ}    ISO 8601 timezone in +/-hh:mm format
:::
:::         {ISOTS}  same as {ISOTS.}
:::
:::         {ISOTS.} YYYYMMDDThhmmss.fff+hhss
:::                  Compressed ISO 8601 date/time (timestamp) with milliseconds
:::                  and time zone, using . as decimal mark
:::
:::         {ISOTS,} YYYYMMDDThhmmss,fff+hhss
:::                  Compressed ISO 8601 date/time (timestamp) with milliseconds
:::                  and time zone, using , as decimal mark
:::
:::         {ISODT}  YYYYMMDD
:::                  Compressed ISO 8601 date format
:::
:::         {ISOTM}  same as {ISOTM.}
:::
:::         {ISOTM.} hhmmss.fff
:::                  Compressed ISO 8601 time format with milliseconds,
:::                  using . as decimal mark
:::
:::         {ISOTM,} hhmmss,fff
:::                  Compressed ISO 8601 time format with milliseconds,
:::                  using , as decimal mark
:::
:::         {ISOTZ}  +hhmm
:::                  Compressed ISO 8601 timezone format
:::
:::         {ISOWY}  yyyy
:::                  ISO 8601 week numbering year
:::                  Dec 29, 30, or 31 may belong to the next Jan year
:::                  Jan 01, 02, or 03 may belong to the prior Dec year
:::
:::         {ISOWK}  ww
:::                  ISO 8601 week number
:::                  Week 01 is the week with the year's first Thursday
:::
:::         {ISOWD}  d
:::                  ISO 8601 day of week: 1=Monday, 7=Sunday
:::
:::         {ISODTW} yyyyWwwd
:::                  Compressed ISO 8601 week date format
:::
:::         {ISODTO} YYYYDDD
:::                  Compressed ISO 8601 ordinal date format
:::
:::         {ISO-TS} same as {ISO-TS.}
:::
:::         {ISO-TS.} YYYY-MM-DDThh:mm:ss.fff+hh:ss
:::                  ISO 8601 date/time (timestamp) with milliseconds and time zone
:::                  using . as decimal mark
:::
:::         {ISO-TS,} YYYY-MM-DDThh:mm:ss,fff+hh:ss
:::                  ISO 8601 date/time (timestamp) with milliseconds and time zone
:::                  using , as decimal mark
:::
:::         {ISO-DT} YYYY-MM-DD
:::                  ISO 8601 date format
:::
:::         {ISO-TM} same as {ISO-TM.}
:::
:::         {ISO-TM.} hh:mm:ss.fff
:::                  ISO 8601 time format with milliseconds,
:::                  using . as decimal mark
:::
:::         {ISO-TM,} hh:mm:ss,fff
:::                  ISO 8601 time format with milliseconds,
:::                  using , as decimal mark
:::
:::         {ISO-TZ} +hh:mm
:::                  ISO 8601 timezone  (same as {TZ})
:::
:::         {ISO-DTW} yyyy-Www-d
:::                  ISO 8601 week date format
:::
:::         {ISO-DTO} YYYY-DDD
:::                  ISO 8601 ordinal date format
:::
:::         {UMS}   Milliseconds since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {U}     Same as {US}
:::
:::         {US}    Seconds since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {UM}    Minutes since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {UH}    Hours since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {UD}    Days since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {USD}   Decimal seconds since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {UMD}   Decimal minutes since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {UHD}   Decimal hours since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {UDD}   Decimal days since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {{}     A { character
:::
:::    -R ReturnVariable
:::
:::       Save the timestamp in ReturnVariable instead of displaying it.
:::       ReturnVariable is unchanged if an error occurs.
:::       Default is empty, meaning print to screen.
:::
:::    -WKD "Abbreviated day of week list"
:::
:::       Override the default day abbreviations with a space delimited,
:::       quoted list, starting with Sun.
:::       Default is mixed case, 3 character English day abbreviations.
:::
:::    -WEEKDAY "Day of week list"
:::
:::       Override the default day names with a space delimited, quoted list,
:::       starting with Sunday.
:::       Default is mixed case English day names.
:::
:::    -MTH "Abbreviated month list"
:::
:::       Override the default month abbreviations with a space delimited,
:::       quoted list, starting with Jan.
:::       Default is mixed case, 3 character English month abbreviations.
:::
:::    -MONTH "Month list"
:::
:::       Override the default month names with a space delimited, quoted list,
:::       starting with January.
:::       Default is mixed case English month names.
:::
:::
:::  GetTimestamp.bat was written by Dave Benham and originally posted at
:::  http://www.dostips.com/forum/viewtopic.php?f=3&t=4847
:::

============= :Batch portion ===========
@echo off
setlocal enableDelayedExpansion

:: Define options
set ^"options=^
 -?:^
 -??:^
 -v:^
 -u:^
 -z:""^
 -f:"{ISO-TS}"^
 -d:""^
 -oy:""^
 -om:""^
 -od:""^
 -oh:""^
 -on:""^
 -os:""^
 -of:""^
 -r:""^
 -wkd:"Sun Mon Tue Wed Thu Fri Sat"^
 -weekday:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday"^
 -mth:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"^
 -month:"January February March April May June July August September October November December"^"

:: Set default option values
for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do (
  if defined GetTimestamp%%A (set "%%A=!GetTimestamp%%A!") else set "%%A=%%~B"
)
set "-?="
set "-??="

:: Get options
:loop
if not "%~1"=="" (
  set "arg=%~1"
  if "!arg:~0,1!" equ "/" set "arg=-!arg:~1!"
  for /f delims^=^ eol^= %%A in ("!arg!") do set "test=!options:*%%A:=! "
  if "!test!"=="!options! " (
      >&2 echo Error: Invalid option %~1. Use %~nx0 -? to get help.
      exit /b 1
  ) else if "!test:~0,1!"==" " (
      set "!arg!=1"
      if /i "!arg!" equ "-U" set "-z="
  ) else (
      set "!arg!=%~2"
      shift /1
  )
  shift /1
  goto :loop
)
if defined -z set "-u=1"
if defined -r set "%-r%="

:: Display paged help
if defined -?? (
  (for /f "delims=: tokens=*" %%A in ('findstr "^:::" "%~f0"') do @echo(%%A)|more /e
  exit /b 0
) 2>nul

:: Display help
if defined -? (
  for /f "delims=: tokens=*" %%A in ('findstr "^:::" "%~f0"') do echo(%%A
  exit /b 0
)

:: Display version
if defined -v (
  for /f "tokens=* delims=:" %%A in ('findstr "^::getTimestamp\.bat" "%~f0"') do @echo(%%A
  exit /b 0
)

:: Execute the JScript script and return the result
for /f "delims=" %%A in ('cscript //E:JScript //nologo "%~f0"') do (
  endlocal
  if "%-R%" neq "" (set "%-R%=%%A") else (echo(%%A)
  exit /b 0
)
exit /b 1;


************ JScript portion ***********/
var env  = WScript.CreateObject("WScript.Shell").Environment("Process"),
    utc  = env('-U'),
    wkd     = env('-WKD').split(' '),
    weekday = env('-WEEKDAY').split(' '),
    mth     = env('-MTH').split(' '),
    month   = env('-MONTH').split(' '),
    stderr  = WScript.StdErr,
    y,m,d,w,h,h12,n,s,f,u,z,zs,za,
    pc=':', pcm=',', pd='-', pp='.', p2='00', p3='000', p4='0000';

if (wkd.length!=7)     badOp('-WKD');
if (weekday.length!=7) badOp('-WEEKDAY');
if (mth.length!=12)    badOp('-MTH');
if (month.length!=12)  badOp('-MONTH');

try {
  var dt = eval('new Date('+env('-D')+')');
} catch(e) {
} finally {
  if (isNaN(dt)) badOp('-D');
}

if (env('-OY')) dt.setUTCFullYear(     dt.getUTCFullYear()    +getNum('-OY') );
if (env('-OM')) dt.setUTCMonth(        dt.getUTCMonth()       +getNum('-OM') );
if (env('-OD')) dt.setUTCDate(         dt.getUTCDate()        +getNum('-OD') );
if (env('-OH')) dt.setUTCHours(        dt.getUTCHours()       +getNum('-OH') );
if (env('-ON')) dt.setUTCMinutes(      dt.getUTCMinutes()     +getNum('-ON') );
if (env('-OS')) dt.setUTCSeconds(      dt.getUTCSeconds()     +getNum('-OS') );
if (env('-OF')) dt.setUTCMilliseconds( dt.getUTCMilliseconds()+getNum('-OF') );
if (env('-Z'))  dt.setUTCMinutes(      dt.getUTCMinutes()  +(z=getNum('-Z')) );

y = utc ? dt.getUTCFullYear(): dt.getFullYear();
m = utc ? dt.getUTCMonth()   : dt.getMonth();
d = utc ? dt.getUTCDate()    : dt.getDate();
w = utc ? dt.getUTCDay()     : dt.getDay();
h = utc ? dt.getUTCHours()   : dt.getHours();
n = utc ? dt.getUTCMinutes() : dt.getMinutes();
s = utc ? dt.getUTCSeconds() : dt.getSeconds();
f = utc ? dt.getUTCMilliseconds() : dt.getMilliseconds();
u = dt.getTime();

h12 = h%12;
if (!h12) h12=12;

if (z==undefined) if (utc) z=0; else z=-dt.getTimezoneOffset();
zs = z<0 ? '-' : '+';
za = Math.abs(z);

WScript.echo( env('-F').replace( /\{(.*?)\}/gi, repl ) );
WScript.Quit(0);

function lpad( val, pad ) {
  var rtn=val.toString();
  return (rtn.length<pad.length) ? (pad+rtn).slice(-pad.length) : val;
}

function getNum( v ) {
  var rtn;
  try {
    rtn = Number(eval(env(v)));
  } catch(e) {
  } finally {
    if (isNaN(rtn-rtn)) badOp(v);
    return rtn;
  }
}

function badOp(option) {
  stderr.WriteLine('Error: Invalid '+option+' value');
  WScript.Quit(1);
}

function trunc( n ) { return Math[n>0?"floor":"ceil"](n); }

function weekNum(dt) {
   var dt2 = new Date(dt.valueOf());
   var day = (dt.getDay()+6)%7;
   dt2.setDate(dt2.getDate()-day+3);
   var now = dt2.valueOf();
   dt2.setMonth(0, 1);
   if (dt2.getDay() != 4) {
      dt2.setMonth( 0, (11-dt2.getDay())%7 + 1 );
   }
   return 1 + Math.ceil((now-dt2.valueOf())/604800000);
}

function weekYr(dt) {
   var dt2 = new Date(dt.valueOf());
   dt2.setDate(dt2.getDate()+3-(dt.getDay()+6)%7);
   return dt2.getFullYear();
}

function repl($0,$1) {
  switch ($1.toUpperCase()) {
    case 'YYYY' : return lpad(y,p4);
    case 'YY'   : return (p2+y.toString()).slice(-2);
    case 'Y'    : return y.toString();
    case 'MM'   : return lpad(m+1,p2);
    case 'M'    : return (m+1).toString();
    case 'DD'   : return lpad(d,p2);
    case 'D'    : return d.toString();
    case 'W'    : return w.toString();
    case 'DY'   : return trunc(((new Date(y,m,d)).getTime()-(new Date(y,0,0)).getTime())/86400000).toString();
    case 'DDY'  : return lpad( trunc(((new Date(y,m,d)).getTime()-(new Date(y,0,0)).getTime())/86400000), p3);
    case 'HH'   : return lpad(h,p2);
    case 'H'    : return h.toString();
    case 'HH12' : return lpad(h12,p2);
    case 'H12'  : return h12.toString();
    case 'NN'   : return lpad(n,p2);
    case 'N'    : return n.toString();
    case 'SS'   : return lpad(s,p2);
    case 'S'    : return s.toString();
    case 'FFF'  : return lpad(f,p3);
    case 'F'    : return f.toString();
    case 'AM'   : return h>=12 ? 'PM' : 'AM';
    case 'PM'   : return h>=12 ? 'pm' : 'am';
    case 'UMS'  : return u.toString();
    case 'USD'  : return (u/1000).toString();
    case 'UMD'  : return (u/1000/60).toString();
    case 'UHD'  : return (u/1000/60/60).toString();
    case 'UDD'  : return (u/1000/60/60/24).toString();
    case 'U'    :
    case 'US'   : return trunc(u/1000).toString();
    case 'UM'   : return trunc(u/1000/60).toString();
    case 'UH'   : return trunc(u/1000/60/60).toString();
    case 'UD'   : return trunc(u/1000/60/60/24).toString();
    case 'ZZZZ' : return zs+lpad(za,p3);
    case 'Z'    : return z.toString();
    case 'ZS'   : return zs;
    case 'ZH'   : return lpad(trunc(za/60),p2);
    case 'ZM'   : return lpad(za%60,p2);
    case 'TZ'   :
    case 'ISO-TZ' : return ''+zs+lpad(trunc(za/60),p2)+pc+lpad(za%60,p2);
    case 'ISOTS'  :
    case 'ISOTS.' : return ''+lpad(y,p4)+lpad(m+1,p2)+lpad(d,p2)+'T'+lpad(h,p2)+lpad(n,p2)+lpad(s,p2)+pp+lpad(f,p3)+zs+lpad(trunc(za/60),p2)+lpad(za%60,p2);
    case 'ISOTS,' : return ''+lpad(y,p4)+lpad(m+1,p2)+lpad(d,p2)+'T'+lpad(h,p2)+lpad(n,p2)+lpad(s,p2)+pcm+lpad(f,p3)+zs+lpad(trunc(za/60),p2)+lpad(za%60,p2);
    case 'ISODT'  : return ''+lpad(y,p4)+lpad(m+1,p2)+lpad(d,p2);
    case 'ISOTM'  :
    case 'ISOTM.' : return ''+lpad(h,p2)+lpad(n,p2)+lpad(s,p2)+pp+lpad(f,p3);
    case 'ISOTM,' : return ''+lpad(h,p2)+lpad(n,p2)+lpad(s,p2)+pcm+lpad(f,p3);
    case 'ISOTZ'  : return ''+zs+lpad(trunc(za/60),p2)+lpad(za%60,p2);
    case 'ISO-TS' :
    case 'ISO-TS.': return ''+lpad(y,p4)+pd+lpad(m+1,p2)+pd+lpad(d,p2)+'T'+lpad(h,p2)+pc+lpad(n,p2)+pc+lpad(s,p2)+pp+lpad(f,p3)+zs+lpad(trunc(za/60),p2)+pc+lpad(za%60,p2);
    case 'ISO-TS,': return ''+lpad(y,p4)+pd+lpad(m+1,p2)+pd+lpad(d,p2)+'T'+lpad(h,p2)+pc+lpad(n,p2)+pc+lpad(s,p2)+pcm+lpad(f,p3)+zs+lpad(trunc(za/60),p2)+pc+lpad(za%60,p2);
    case 'ISO-DT' : return ''+lpad(y,p4)+pd+lpad(m+1,p2)+pd+lpad(d,p2);
    case 'ISO-TM' :
    case 'ISO-TM.': return ''+lpad(h,p2)+pc+lpad(n,p2)+pc+lpad(s,p2)+pp+lpad(f,p3);
    case 'ISO-TM,': return ''+lpad(h,p2)+pc+lpad(n,p2)+pc+lpad(s,p2)+pcm+lpad(f,p3);
    case 'ISOWY'  : return ''+lpad(weekYr(dt),p4);
    case 'ISOWK'  : return ''+lpad(weekNum(dt),p2);
    case 'ISOWD'  : return ''+((w+6)%7+1);
    case 'ISODTW' : return ''+lpad(weekYr(dt),p4)+'W'+lpad(weekNum(dt),p2)+((w+6)%7+1);
    case 'ISODTO' : return ''+lpad(y,p4)+lpad( trunc(((new Date(y,m,d)).getTime()-(new Date(y,0,0)).getTime())/86400000), p3);
    case 'ISO-DTW': return ''+lpad(weekYr(dt),p4)+pd+'W'+lpad(weekNum(dt),p2)+pd+((w+6)%7+1);
    case 'ISO-DTO': return ''+lpad(y,p4)+pd+lpad( trunc(((new Date(y,m,d)).getTime()-(new Date(y,0,0)).getTime())/86400000), p3);
    case 'WEEKDAY': return weekday[w];
    case 'WKD'    : return wkd[w];
    case 'MONTH'  : return month[m];
    case 'MTH'    : return mth[m];
    case '{'      : return $1;
    default       : return $0;
  }
}


Dave Benham

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: getTimestamp.bat for time and date processing

#40 Post by dbenham » 09 Jul 2016 14:52

foxidrive wrote:Dave, I have a task to add these times one-by-one and get a cumulative result from each step, but also adding the day in a 2 digit zero padded figure.

Can you give me a clue please?

Code: Select all

00:00:00:000
01:25:56.606
01:29:11.410
01:30:35.314
01:28:31.956
00:46:53.378
01:30:01.046
01:30:21.032
01:32:05.801
01:30:50.729
01:30:44.546
01:31:11.407
01:29:52.438
00:47:12.321
01:40:47.929
01:29:07.127
00:47:58.977
01:31:00.337
01:31:01.505
01:29:55.248
01:32:21.105


It is fairly straight forward (once you have my v2.5 release that fixes a bug with offset computations).

You need to do the computations as miliseconds past midnight 1/1/1970 UTC.

The standard string date parser recognizes dates like 'mm/dd/yyyy HH:MM:SS UTC', but unfortunately it does not recognize fractional seconds. So you need to add the fractional seconds using the -OF option. You also keep a running tally of the total milliseconds, which needs to be added to each value as well. I initialize my total to 0 at the start.

So I use a simple FOR loop to iterate the raw strings, and a FOR /F to separate the fractional seconds from the rest of the time.

Note that JScript treats 0 prefixed numbers as octal (unless it sees an 8 or 9 digit, in which case it switches to decimal - very screwy). So I use the standard trick of prefixing the string with 1 and then subtracting 1000.

So the first JREPL treats the time interval as the number of milliseconds past midnight 1/1/1970 UTC, and also adds the previous total value, and stores the result as the new total.

The 2nd JREPL simply formats the time value appropriately. I don't have a built in way to specify the number of digits to display for the {UD} value, so I use the standard trick of prefixing the value with leading zeros, and then use a variable substring op to get the correct value.

Code: Select all

@echo off
setlocal enableDelayedExpansion
set "total=0"  cumulative total in msec
for %%T in (
  00:00:00.000
  01:25:56.606
  01:29:11.410
  01:30:35.314
  01:28:31.956
  00:46:53.378
  01:30:01.046
  01:30:21.032
  01:32:05.801
  01:30:50.729
  01:30:44.546
  01:31:11.407
  01:29:52.438
  00:47:12.321
  01:40:47.929
  01:29:07.127
  00:47:58.977
  01:31:00.337
  01:31:01.505
  01:29:55.248
  01:32:21.105
) do for /f "delims=. tokens=1,2" %%A in ("%%T") do (
  call getTimestamp -d "'1/1/1970 %%A UTC'" -of "1%%B-1000+!total!" -f "{ums}" -r total
  call getTimestamp -d !total! -u -f 0{ud}:{hh}:{nn}:{ss}.{fff} -r result
  echo !result:~-15!
)
--OUTPUT--

Code: Select all

00:00:00:00.000
00:01:25:56.606
00:02:55:08.016
00:04:25:43.330
00:05:54:15.286
00:06:41:08.664
00:08:11:09.710
00:09:41:30.742
00:11:13:36.543
00:12:44:27.272
00:14:15:11.818
00:15:46:23.225
00:17:16:15.663
00:18:03:27.984
00:19:44:15.913
00:21:13:23.040
00:22:01:22.017
00:23:32:22.354
01:01:03:23.859
01:02:33:19.107
01:04:05:40.212


The technique can easily be extended to support day values in your input. I add the days into the computation using the -OD option. Obviously I had to modify my loop parsing a bit. I opted to set my day width to 3 characters, with leading spaces instead of zeros.

Code: Select all

@echo off
setlocal enableDelayedExpansion
set "total=0"  cumulative total in msec
for %%T in (
  0:00:00:00.000
  0:01:25:56.606
  1:01:29:11.410
  0:01:30:35.314
  0:01:28:31.956
 19:00:46:53.378
  0:01:30:01.046
  0:01:30:21.032
  0:01:32:05.801
 13:01:30:50.729
  0:01:30:44.546
  9:01:31:11.407
 27:01:29:52.438
  0:00:47:12.321
 65:01:40:47.929
  0:01:29:07.127
  0:00:47:58.977
  0:01:31:00.337
  0:01:31:01.505
  0:01:29:55.248
  0:01:32:21.105
) do for /f "delims=: tokens=1*" %%D in ("%%T") do for /f "delims=. tokens=1,2" %%A in ("%%E") do (
  call getTimestamp -d "'1/1/1970 %%A UTC'" -od %%D -of "1%%B-1000+!total!" -f "{ums}" -r total
  call getTimestamp -d !total! -u -f "  {ud}:{hh}:{nn}:{ss}.{fff}" -r result
  echo !result:~-16!
)
--OUTPUT--

Code: Select all

  0:00:00:00.000
  0:01:25:56.606
  1:02:55:08.016
  1:04:25:43.330
  1:05:54:15.286
 20:06:41:08.664
 20:08:11:09.710
 20:09:41:30.742
 20:11:13:36.543
 33:12:44:27.272
 33:14:15:11.818
 42:15:46:23.225
 69:17:16:15.663
 69:18:03:27.984
134:19:44:15.913
134:21:13:23.040
134:22:01:22.017
134:23:32:22.354
135:01:03:23.859
135:02:33:19.107
135:04:05:40.212


Dave Benham

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: getTimestamp.bat for time and date processing

#41 Post by foxidrive » 10 Jul 2016 06:26

Thank you Dave, you've been very kind.

That's great! :thumbsup:

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: getTimestamp.bat for time and date processing

#42 Post by dbenham » 10 Jul 2016 12:33

My last version fixed a problem with the date/time offset options, but it also lost the ability to add days or months without changing the local time. Adding days and months results in a change that is an exact multiple of 24 hours, so the local hour may change if the daylight savings conditions changes.

For example, if the timestamp were 1AM on 1/10/2016 on the U.S. coast where I live (6:00 UTC), then use of -OM 6 (add 6 months) would result in a local time of 2AM instead of 1AM because of the switch-over from standard time to daylight savings. Note that UTC time would be perfectly fine, since it does not observe daylight savings - the UTC time would remain at 6:00.

I've added the -OLM and -OLD options to allow addition of local months and days in a way that preserves the local hour. Thus the change may not be an even multiple of 24 hours. So going back to my example of 1/10/2016 1:00 AM EST, adding -OLM 6 would preserve the local time of 1:00 (but the UTC time will have gone from 6:00 to 5:00).

getTimestamp.bat version 2.6

Code: Select all

@if (@X)==(@Y) @end  /* harmless hybrid line that begins a JScript comment
@goto :batch
::
::getTimestamp.bat version 2.6 by Dave Benham
::
::  Release History:
::    2.6 2016-07-10 - Added -OLM and -OLD to allow addition of months/years
::                     without changing the local hour. In other words, the
::                     computation compensates for changes in dayling savings
::                     conditions.
::    2.5 2016-07-09 - Fixed bug with offset computations when the before and
::                     after have different time zones due to daylight savings.
::    2.4 2015-11-27 - Added formats to support comma as decimal mark in
::                     ISO 8601 time and timestamp formats.
::                     Added formats to support ISO 8601 week dates
::                     and ordinal dates.
::                     Rearranged documentation, and added examples for
::                     base date specified as a list of numeric values.
::    2.3 2015-07-11 - Added {ISO-xx}, {ISOxx}, {DY} and {DDY} formats
::                     Added -?? (paged help) option
::                     Allow user defined default option values by defining
::                     variables of the form "GetTimestamp-OPTION=VALUE"
::    2.2 2014-12-03 - Doc fix: -R ReturnVariable is unchanged if err occurs
::    2.1 2014-12-03 - Added GOTO at top to increase performance (32% faster)
::    2.0 2014-12-02 - Major rewrite: most code now in JScript (25% faster)
::                     Better error handling
::                     May now use /Option or -Option
::                     Added -V option
::                     Added {{} format value to enable unambiguous { literal
::    1.1 ????-??-?? - Added -Z option and obscure bug fixes
::    1.0 2013-07-17 - Initial release
::
::============ Documentation ===========
:::
:::getTimestamp  [-option [value]]...
:::
:::  Displays a formatted timestamp. Defaults to the current local date
:::  and time using an ISO 8601 format with milliseconds, time zone
:::  and punctuation, using period as a decimal mark.
:::
:::  Returned ERRORLEVEL is 0 upon success, 1 if failure.
:::
:::  Options may be prefaced with - or /
:::
:::  All options have default values. The default value can be overridden by
:::  defining an evironment variable of the form "GetTimestamp-OPTION=VALUE".
:::  For example, upper case English weekday abbreviations can be specified as
:::  the default by defining "GetTimestamp-WKD=SUN MON TUE WED THU FRI SAT".
:::
:::  Command line option values take precedence, followed by environment variable
:::  defaults, followed by built in defaults.
:::
:::  The following options are all case insensitive:
:::
:::    -?  : Prints this documentation for getTimestamp
:::
:::    -?? : Prints this documentation with pagination via MORE
:::
:::    -V  : Prints the version of getTimeStamp
:::
:::    -D DateSpec
:::
:::       Specify the base date and time.
:::       Default value is current local date and time.
:::       The DateSpec supports many formats:
:::
:::         ""    (no value)
:::
:::           Current date and time - the default
:::
:::         milliseconds
:::
:::           A JScript numeric expression that represents the number of
:::           milliseconds since 1970-01-01 00:00:00 UTC.
:::           Decimal values are truncated.
:::           Negative values represent dates prior to 1970-01-01.
:::
:::         "'Date [Time] [TimeZone]'"
:::
:::           A string representation of the date and time. The date information
:::           is required, the time and time zone are optional. Missing time info
:::           is assumed to be 0 (midnight). Missing time zone info is assumed to
:::           be local time zone.
:::
:::           The Date, Time, and TimeZone information can be represented as any
:::           string that is accepted by the JScript Date.Parse() method.
:::           There are many formatting options. Documentation is available at:
:::           http://msdn.microsoft.com/en-us/library/k4w173wk(v=vs.84).aspx
:::
:::           Examples of equivalent representations of Midnight on January 4,
:::           2013 assuming local time zone is U.S Eastern Standard Time (EST):
:::
:::             '1-4-2013'                    Defaults to local time zone
:::             "'January 4, 2013 EST'"       Explicit Eastern Std Time (US)
:::             "'2013/1/4 -05'"              Explicit Eastern Std Time (US)
:::             "'Jan 3 2013 23: CST'"        Central Standard Time (US)
:::             "'2013 3 Jan 9:00 pm -0800'"  Pacific Standard Time (US)
:::             "'01/04/2013 05:00:00 UTC'"   Universal Coordinated Time
:::             "'1/4/2013 05:30 +0530'"      India Standard Time
:::
:::         "year, month[, day[, hour[, minute[, second[, millisecond]]]]]"
:::
:::           A comma delimited list of numeric JScript expressions representing
:::           various components of date and time. Year and month are required,
:::           the rest are optional. Missing values are treated as 0.
:::           Decimal values are truncated. A 0 month represents January.
:::           A 1 day represents the first day of the month. A 0 day represents
:::           the last day of the prior month. The date/time value is always
:::           in local time. There is no mechanism to specify a time zone.
:::
:::           Examples: (all in local time)
:::             "2012,0,1,12,45,3,121"  12:45:03.121 on Jan 1, 2012
:::             "2012,0,1,12"           Noon on Jan 1, 2012
:::             "2012,1,1"              Midnight on Feb 1, 2012
:::             "2012,2,0"              Midnight on Feb 29, 2012 (last day of Feb)
:::             "2012,2"                Midnight on Feb 29, 2012 (last day of Feb)
:::
:::           The ability to use JScript expressions makes it convenient to do
:::           date and time offset computations in a very compact form.
:::
:::           For example, starting with:
:::             "2015,8,7,14,5"        Sep 7, 2015 at 14:05:00
:::
:::           It is simple to subtract 30 days and 30 minutes from the above:
:::             "2015,8,7-30,14,5-30"  Aug 8, 2015 at 13:35:00
:::
:::    -U  : Returns a UTC timestamp instead of local timestamp.
:::          Default is a local timestamp.
:::
:::    -Z TimeZoneMinuteOffset
:::
:::       Returns the timestamp using the specified time zone offset.
:::       TimeZoneMinuteOffset is a JScript numeric expression that
:::       represents the number of minutes offset from UTC.
:::       Decimal values are truncated.
:::       Default is empty, meaning local timezone.
:::
:::    -OY YearOffset
:::
:::       Specify the number of years to offset the base date/time.
:::       The JScript numeric expression is truncated to an integral number.
:::       Default is 0
:::
:::    -OM MonthOffset
:::
:::       Specify the number of months to offset the base date/time, ignoring
:::       local daylight savings conditions. The change is guaranteed to be a
:::       multiple of 24 hours. The JScript numeric expression is truncated to
:::       an integral number. Default is 0
:::
:::    -OLM LocalMonthOffset
:::
:::       Specify the number of months to offset the base date/time, taking into
:::       account local daylight savings conditions. The change may not be a
:::       multiple of 24 hours if the offset results in a change from standard
:::       to daylight savings, or vice versa. The JScript numeric expression is
:::       truncated to an integral number. Default is 0
:::
:::    -OD DayOffset
:::
:::       Specify the number of days to offset the base date/time, ignoring
:::       local daylight savings conditions. The change is guaranteed to be a
:::       multiple of 24 hours. The JScript numeric expression is truncated to
:::       an integral number. Default is 0
:::
:::    -OLD LocalDayOffset
:::
:::       Specify the number of days to offset the base date/time, taking into
:::       account local daylight savings conditions. The change may not be a
:::       multiple of 24 hours if the offset results in a change from standard
:::       to daylight savings, or vice versa. The JScript numeric expression is
:::       truncated to an integral number. Default is 0
:::
:::    -OH HourOffset
:::
:::       Specify the number of hours to offset the base date/time.
:::       The JScript numeric expression is truncated to an integral number.
:::       Default is 0
:::
:::    -ON MinuteOffset
:::
:::       Specify the number of minutes to offset the base date/time.
:::       The JScript numeric expression is truncated to an integral number.
:::       Default is 0
:::
:::    -OS SecondOffset
:::
:::       Specify the number of seconds to offset the base date/time.
:::       The JScript numeric expression is truncated to an integral number.
:::       Default is 0
:::
:::    -OF MillisecondOffset
:::
:::       Specify the number of milliseconds to offset the base date/time.
:::       The JScript numeric expression is truncated to an integral number.
:::       Default is 0
:::
:::    -F FormatString
:::
:::       Specify the timestamp format.
:::       Default is "{ISO-TS.}"
:::       Strings within braces are dynamic components.
:::       All other strings are literals.
:::       Available components (case insensitive) are:
:::
:::         {YYYY}  4 digit year, zero padded
:::
:::         {YY}    2 digit year, zero padded
:::
:::         {Y}     year without zero padding
:::
:::         {MONTH} month name, as preferentially specified by:
:::                    1) -MONTH option
:::                    2) GetTimestamp-MONTH environment variable
:::                    3) Mixed case, English month names
:::
:::         {MTH}   month abbreviation, as preferentially specified by:
:::                    1) -MTH option
:::                    2) GetTimestamp-MTH environment variable
:::                    3) Mixed case, English month abbreviations
:::
:::         {MM}    2 digit month number, zero padded
:::
:::         {M}     month number without zero padding
:::
:::         {WEEKDAY} day of week name, as preferentially specified by:
:::                    1) -WEEKDAY option
:::                    2) GetTimestamp-WEEKDAY environment variable
:::                    3) Mixed case, English day names
:::
:::         {WKD}   day of week abbreviation, as preferentially specified by:
:::                    1) -WKD option
:::                    2) GetTimestamp-WKD environment variable
:::                    3) Mixed case, English day abbreviations
:::
:::         {W}     day of week number: 0=Sunday, 6=Saturday
:::
:::         {DD}    2 digit day of month number, zero padded
:::
:::         {D}     day of month number, without zero padding
:::
:::         {DDY}   3 digit day of year number, zero padded
:::
:::         {DY}    day of year number, without zero padding
:::
:::         {HH}    2 digit hours, 24 hour format, zero padded
:::
:::         {H}     hours, 24 hour format without zero padding
:::
:::         {HH12}  2 digit hours, 12 hour format, zero padded
:::
:::         {H12}   hours, 12 hour format without zero padding
:::
:::         {NN}    2 digit minutes, zero padded
:::
:::         {N}     minutes without padding
:::
:::         {SS}    2 digit seconds, zero padded
:::
:::         {S}     seconds without padding
:::
:::         {FFF}   3 digit milliseconds, zero padded
:::
:::         {F}     milliseconds without padding
:::
:::         {AM}    AM or PM in upper case
:::
:::         {PM}    am or pm in lower case
:::
:::         {ZZZZ}  timezone expressed as minutes offset from UTC,
:::                 zero padded to 3 digits with sign
:::
:::         {Z}     timzone expressed as minutes offset from UTC without padding
:::
:::         {ZS}    ISO 8601 timezone sign
:::
:::         {ZH}    ISO 8601 timezone hours (no sign)
:::
:::         {ZM}    ISO 8601 timezone minutes (no sign)
:::
:::         {TZ}    ISO 8601 timezone in +/-hh:mm format
:::
:::         {ISOTS}  same as {ISOTS.}
:::
:::         {ISOTS.} YYYYMMDDThhmmss.fff+hhss
:::                  Compressed ISO 8601 date/time (timestamp) with milliseconds
:::                  and time zone, using . as decimal mark
:::
:::         {ISOTS,} YYYYMMDDThhmmss,fff+hhss
:::                  Compressed ISO 8601 date/time (timestamp) with milliseconds
:::                  and time zone, using , as decimal mark
:::
:::         {ISODT}  YYYYMMDD
:::                  Compressed ISO 8601 date format
:::
:::         {ISOTM}  same as {ISOTM.}
:::
:::         {ISOTM.} hhmmss.fff
:::                  Compressed ISO 8601 time format with milliseconds,
:::                  using . as decimal mark
:::
:::         {ISOTM,} hhmmss,fff
:::                  Compressed ISO 8601 time format with milliseconds,
:::                  using , as decimal mark
:::
:::         {ISOTZ}  +hhmm
:::                  Compressed ISO 8601 timezone format
:::
:::         {ISOWY}  yyyy
:::                  ISO 8601 week numbering year
:::                  Dec 29, 30, or 31 may belong to the next Jan year
:::                  Jan 01, 02, or 03 may belong to the prior Dec year
:::
:::         {ISOWK}  ww
:::                  ISO 8601 week number
:::                  Week 01 is the week with the year's first Thursday
:::
:::         {ISOWD}  d
:::                  ISO 8601 day of week: 1=Monday, 7=Sunday
:::
:::         {ISODTW} yyyyWwwd
:::                  Compressed ISO 8601 week date format
:::
:::         {ISODTO} YYYYDDD
:::                  Compressed ISO 8601 ordinal date format
:::
:::         {ISO-TS} same as {ISO-TS.}
:::
:::         {ISO-TS.} YYYY-MM-DDThh:mm:ss.fff+hh:ss
:::                  ISO 8601 date/time (timestamp) with milliseconds and time zone
:::                  using . as decimal mark
:::
:::         {ISO-TS,} YYYY-MM-DDThh:mm:ss,fff+hh:ss
:::                  ISO 8601 date/time (timestamp) with milliseconds and time zone
:::                  using , as decimal mark
:::
:::         {ISO-DT} YYYY-MM-DD
:::                  ISO 8601 date format
:::
:::         {ISO-TM} same as {ISO-TM.}
:::
:::         {ISO-TM.} hh:mm:ss.fff
:::                  ISO 8601 time format with milliseconds,
:::                  using . as decimal mark
:::
:::         {ISO-TM,} hh:mm:ss,fff
:::                  ISO 8601 time format with milliseconds,
:::                  using , as decimal mark
:::
:::         {ISO-TZ} +hh:mm
:::                  ISO 8601 timezone  (same as {TZ})
:::
:::         {ISO-DTW} yyyy-Www-d
:::                  ISO 8601 week date format
:::
:::         {ISO-DTO} YYYY-DDD
:::                  ISO 8601 ordinal date format
:::
:::         {UMS}   Milliseconds since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {U}     Same as {US}
:::
:::         {US}    Seconds since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {UM}    Minutes since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {UH}    Hours since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {UD}    Days since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {USD}   Decimal seconds since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {UMD}   Decimal minutes since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {UHD}   Decimal hours since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {UDD}   Decimal days since 1970-01-01 00:00:00.000 UTC.
:::                 Negative numbers represent days prior to 1970-01-01.
:::                 This value is unaffected by the -U option.
:::                 This value should not be used with the -Z option
:::
:::         {{}     A { character
:::
:::    -R ReturnVariable
:::
:::       Save the timestamp in ReturnVariable instead of displaying it.
:::       ReturnVariable is unchanged if an error occurs.
:::       Default is empty, meaning print to screen.
:::
:::    -WKD "Abbreviated day of week list"
:::
:::       Override the default day abbreviations with a space delimited,
:::       quoted list, starting with Sun.
:::       Default is mixed case, 3 character English day abbreviations.
:::
:::    -WEEKDAY "Day of week list"
:::
:::       Override the default day names with a space delimited, quoted list,
:::       starting with Sunday.
:::       Default is mixed case English day names.
:::
:::    -MTH "Abbreviated month list"
:::
:::       Override the default month abbreviations with a space delimited,
:::       quoted list, starting with Jan.
:::       Default is mixed case, 3 character English month abbreviations.
:::
:::    -MONTH "Month list"
:::
:::       Override the default month names with a space delimited, quoted list,
:::       starting with January.
:::       Default is mixed case English month names.
:::
:::
:::  GetTimestamp.bat was written by Dave Benham and originally posted at
:::  http://www.dostips.com/forum/viewtopic.php?f=3&t=4847
:::

============= :Batch portion ===========
@echo off
setlocal enableDelayedExpansion

:: Define options
set ^"options=^
 -?:^
 -??:^
 -v:^
 -u:^
 -z:""^
 -f:"{ISO-TS}"^
 -d:""^
 -oy:""^
 -om:""^
 -od:""^
 -oh:""^
 -on:""^
 -os:""^
 -of:""^
 -olm:""^
 -old:""^
 -r:""^
 -wkd:"Sun Mon Tue Wed Thu Fri Sat"^
 -weekday:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday"^
 -mth:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"^
 -month:"January February March April May June July August September October November December"^"

:: Set default option values
for %%O in (%options%) do for /f "tokens=1,* delims=:" %%A in ("%%O") do (
  if defined GetTimestamp%%A (set "%%A=!GetTimestamp%%A!") else set "%%A=%%~B"
)
set "-?="
set "-??="

:: Get options
:loop
if not "%~1"=="" (
  set "arg=%~1"
  if "!arg:~0,1!" equ "/" set "arg=-!arg:~1!"
  for /f delims^=^ eol^= %%A in ("!arg!") do set "test=!options:*%%A:=! "
  if "!test!"=="!options! " (
      >&2 echo Error: Invalid option %~1. Use %~nx0 -? to get help.
      exit /b 1
  ) else if "!test:~0,1!"==" " (
      set "!arg!=1"
      if /i "!arg!" equ "-U" set "-z="
  ) else (
      set "!arg!=%~2"
      shift /1
  )
  shift /1
  goto :loop
)
if defined -z set "-u=1"
if defined -r set "%-r%="

:: Display paged help
if defined -?? (
  (for /f "delims=: tokens=*" %%A in ('findstr "^:::" "%~f0"') do @echo(%%A)|more /e
  exit /b 0
) 2>nul

:: Display help
if defined -? (
  for /f "delims=: tokens=*" %%A in ('findstr "^:::" "%~f0"') do echo(%%A
  exit /b 0
)

:: Display version
if defined -v (
  for /f "tokens=* delims=:" %%A in ('findstr "^::getTimestamp\.bat" "%~f0"') do @echo(%%A
  exit /b 0
)

:: Execute the JScript script and return the result
for /f "delims=" %%A in ('cscript //E:JScript //nologo "%~f0"') do (
  endlocal
  if "%-R%" neq "" (set "%-R%=%%A") else (echo(%%A)
  exit /b 0
)
exit /b 1;


************ JScript portion ***********/
var env  = WScript.CreateObject("WScript.Shell").Environment("Process"),
    utc  = env('-U'),
    wkd     = env('-WKD').split(' '),
    weekday = env('-WEEKDAY').split(' '),
    mth     = env('-MTH').split(' '),
    month   = env('-MONTH').split(' '),
    stderr  = WScript.StdErr,
    y,m,d,w,h,h12,n,s,f,u,z,zs,za,
    pc=':', pcm=',', pd='-', pp='.', p2='00', p3='000', p4='0000';

if (wkd.length!=7)     badOp('-WKD');
if (weekday.length!=7) badOp('-WEEKDAY');
if (mth.length!=12)    badOp('-MTH');
if (month.length!=12)  badOp('-MONTH');

try {
  var dt = eval('new Date('+env('-D')+')');
} catch(e) {
} finally {
  if (isNaN(dt)) badOp('-D');
}

if (env('-OY')) dt.setUTCFullYear(     dt.getUTCFullYear()    +getNum('-OY') );
if (env('-OM')) dt.setUTCMonth(        dt.getUTCMonth()       +getNum('-OM') );
if (env('-OD')) dt.setUTCDate(         dt.getUTCDate()        +getNum('-OD') );
if (env('-OH')) dt.setUTCHours(        dt.getUTCHours()       +getNum('-OH') );
if (env('-ON')) dt.setUTCMinutes(      dt.getUTCMinutes()     +getNum('-ON') );
if (env('-OS')) dt.setUTCSeconds(      dt.getUTCSeconds()     +getNum('-OS') );
if (env('-OF')) dt.setUTCMilliseconds( dt.getUTCMilliseconds()+getNum('-OF') );
if (env('-Z'))  dt.setUTCMinutes(      dt.getUTCMinutes()  +(z=getNum('-Z')) );

if (env('-OLM')) dt.setMonth(        dt.getMonth()       +getNum('-OLM') );
if (env('-OLD')) dt.setDate(         dt.getDate()        +getNum('-OLD') );

y = utc ? dt.getUTCFullYear(): dt.getFullYear();
m = utc ? dt.getUTCMonth()   : dt.getMonth();
d = utc ? dt.getUTCDate()    : dt.getDate();
w = utc ? dt.getUTCDay()     : dt.getDay();
h = utc ? dt.getUTCHours()   : dt.getHours();
n = utc ? dt.getUTCMinutes() : dt.getMinutes();
s = utc ? dt.getUTCSeconds() : dt.getSeconds();
f = utc ? dt.getUTCMilliseconds() : dt.getMilliseconds();
u = dt.getTime();

h12 = h%12;
if (!h12) h12=12;

if (z==undefined) if (utc) z=0; else z=-dt.getTimezoneOffset();
zs = z<0 ? '-' : '+';
za = Math.abs(z);

WScript.echo( env('-F').replace( /\{(.*?)\}/gi, repl ) );
WScript.Quit(0);

function lpad( val, pad ) {
  var rtn=val.toString();
  return (rtn.length<pad.length) ? (pad+rtn).slice(-pad.length) : val;
}

function getNum( v ) {
  var rtn;
  try {
    rtn = Number(eval(env(v)));
  } catch(e) {
  } finally {
    if (isNaN(rtn-rtn)) badOp(v);
    return rtn;
  }
}

function badOp(option) {
  stderr.WriteLine('Error: Invalid '+option+' value');
  WScript.Quit(1);
}

function trunc( n ) { return Math[n>0?"floor":"ceil"](n); }

function weekNum(dt) {
   var dt2 = new Date(dt.valueOf());
   var day = (dt.getDay()+6)%7;
   dt2.setDate(dt2.getDate()-day+3);
   var now = dt2.valueOf();
   dt2.setMonth(0, 1);
   if (dt2.getDay() != 4) {
      dt2.setMonth( 0, (11-dt2.getDay())%7 + 1 );
   }
   return 1 + Math.ceil((now-dt2.valueOf())/604800000);
}

function weekYr(dt) {
   var dt2 = new Date(dt.valueOf());
   dt2.setDate(dt2.getDate()+3-(dt.getDay()+6)%7);
   return dt2.getFullYear();
}

function repl($0,$1) {
  switch ($1.toUpperCase()) {
    case 'YYYY' : return lpad(y,p4);
    case 'YY'   : return (p2+y.toString()).slice(-2);
    case 'Y'    : return y.toString();
    case 'MM'   : return lpad(m+1,p2);
    case 'M'    : return (m+1).toString();
    case 'DD'   : return lpad(d,p2);
    case 'D'    : return d.toString();
    case 'W'    : return w.toString();
    case 'DY'   : return trunc(((new Date(y,m,d)).getTime()-(new Date(y,0,0)).getTime())/86400000).toString();
    case 'DDY'  : return lpad( trunc(((new Date(y,m,d)).getTime()-(new Date(y,0,0)).getTime())/86400000), p3);
    case 'HH'   : return lpad(h,p2);
    case 'H'    : return h.toString();
    case 'HH12' : return lpad(h12,p2);
    case 'H12'  : return h12.toString();
    case 'NN'   : return lpad(n,p2);
    case 'N'    : return n.toString();
    case 'SS'   : return lpad(s,p2);
    case 'S'    : return s.toString();
    case 'FFF'  : return lpad(f,p3);
    case 'F'    : return f.toString();
    case 'AM'   : return h>=12 ? 'PM' : 'AM';
    case 'PM'   : return h>=12 ? 'pm' : 'am';
    case 'UMS'  : return u.toString();
    case 'USD'  : return (u/1000).toString();
    case 'UMD'  : return (u/1000/60).toString();
    case 'UHD'  : return (u/1000/60/60).toString();
    case 'UDD'  : return (u/1000/60/60/24).toString();
    case 'U'    :
    case 'US'   : return trunc(u/1000).toString();
    case 'UM'   : return trunc(u/1000/60).toString();
    case 'UH'   : return trunc(u/1000/60/60).toString();
    case 'UD'   : return trunc(u/1000/60/60/24).toString();
    case 'ZZZZ' : return zs+lpad(za,p3);
    case 'Z'    : return z.toString();
    case 'ZS'   : return zs;
    case 'ZH'   : return lpad(trunc(za/60),p2);
    case 'ZM'   : return lpad(za%60,p2);
    case 'TZ'   :
    case 'ISO-TZ' : return ''+zs+lpad(trunc(za/60),p2)+pc+lpad(za%60,p2);
    case 'ISOTS'  :
    case 'ISOTS.' : return ''+lpad(y,p4)+lpad(m+1,p2)+lpad(d,p2)+'T'+lpad(h,p2)+lpad(n,p2)+lpad(s,p2)+pp+lpad(f,p3)+zs+lpad(trunc(za/60),p2)+lpad(za%60,p2);
    case 'ISOTS,' : return ''+lpad(y,p4)+lpad(m+1,p2)+lpad(d,p2)+'T'+lpad(h,p2)+lpad(n,p2)+lpad(s,p2)+pcm+lpad(f,p3)+zs+lpad(trunc(za/60),p2)+lpad(za%60,p2);
    case 'ISODT'  : return ''+lpad(y,p4)+lpad(m+1,p2)+lpad(d,p2);
    case 'ISOTM'  :
    case 'ISOTM.' : return ''+lpad(h,p2)+lpad(n,p2)+lpad(s,p2)+pp+lpad(f,p3);
    case 'ISOTM,' : return ''+lpad(h,p2)+lpad(n,p2)+lpad(s,p2)+pcm+lpad(f,p3);
    case 'ISOTZ'  : return ''+zs+lpad(trunc(za/60),p2)+lpad(za%60,p2);
    case 'ISO-TS' :
    case 'ISO-TS.': return ''+lpad(y,p4)+pd+lpad(m+1,p2)+pd+lpad(d,p2)+'T'+lpad(h,p2)+pc+lpad(n,p2)+pc+lpad(s,p2)+pp+lpad(f,p3)+zs+lpad(trunc(za/60),p2)+pc+lpad(za%60,p2);
    case 'ISO-TS,': return ''+lpad(y,p4)+pd+lpad(m+1,p2)+pd+lpad(d,p2)+'T'+lpad(h,p2)+pc+lpad(n,p2)+pc+lpad(s,p2)+pcm+lpad(f,p3)+zs+lpad(trunc(za/60),p2)+pc+lpad(za%60,p2);
    case 'ISO-DT' : return ''+lpad(y,p4)+pd+lpad(m+1,p2)+pd+lpad(d,p2);
    case 'ISO-TM' :
    case 'ISO-TM.': return ''+lpad(h,p2)+pc+lpad(n,p2)+pc+lpad(s,p2)+pp+lpad(f,p3);
    case 'ISO-TM,': return ''+lpad(h,p2)+pc+lpad(n,p2)+pc+lpad(s,p2)+pcm+lpad(f,p3);
    case 'ISOWY'  : return ''+lpad(weekYr(dt),p4);
    case 'ISOWK'  : return ''+lpad(weekNum(dt),p2);
    case 'ISOWD'  : return ''+((w+6)%7+1);
    case 'ISODTW' : return ''+lpad(weekYr(dt),p4)+'W'+lpad(weekNum(dt),p2)+((w+6)%7+1);
    case 'ISODTO' : return ''+lpad(y,p4)+lpad( trunc(((new Date(y,m,d)).getTime()-(new Date(y,0,0)).getTime())/86400000), p3);
    case 'ISO-DTW': return ''+lpad(weekYr(dt),p4)+pd+'W'+lpad(weekNum(dt),p2)+pd+((w+6)%7+1);
    case 'ISO-DTO': return ''+lpad(y,p4)+pd+lpad( trunc(((new Date(y,m,d)).getTime()-(new Date(y,0,0)).getTime())/86400000), p3);
    case 'WEEKDAY': return weekday[w];
    case 'WKD'    : return wkd[w];
    case 'MONTH'  : return month[m];
    case 'MTH'    : return mth[m];
    case '{'      : return $1;
    default       : return $0;
  }
}


Dave Benham

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: getTimestamp.bat for time and date processing

#43 Post by foxidrive » 06 Aug 2016 07:43

Dave, can I ask you to run your eyes over this please? I think 2 litres of Glenfiddich has detuned my brain. ;)

I found out that Matroska chapters in MKV files don't support day figures, and instead increment the hour figure when the total is over a day: so 25 hours is one day and one hour.

That's what my aim is: to accumulate the hour range instead of what you see here where the hours accumulate to one day and then begin at 01 again.


Do you have some wizardry up your sleeve to handle this?


I noted a strange effect in a few spots where the total is only few minutes different for a 45 odd minute chapter. Or is that my error?

Code: Select all

call getTimestamp /d "'1/1/1970 01:25:56 UTC'" /of 5156606 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:29:11 UTC'" /of 10508016 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:30:35 UTC'" /of 15943330 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:28:31 UTC'" /of 21255286 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 00:46:53 UTC'" /of 24068664 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:30:01 UTC'" /of 29469710 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:30:21 UTC'" /of 34890742 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:32:05 UTC'" /of 40416543 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:30:50 UTC'" /of 45867272 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:30:44 UTC'" /of 51311818 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:31:11 UTC'" /of 56783225 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:29:52 UTC'" /of 62175663 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 00:47:12 UTC'" /of 65007984 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:40:47 UTC'" /of 71055913 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:29:07 UTC'" /of 76403040 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 00:47:58 UTC'" /of 79282017 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:31:00 UTC'" /of 84742354 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:31:01 UTC'" /of 90203859 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:29:55 UTC'" /of 95599107 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"
call getTimestamp /d "'1/1/1970 01:32:21 UTC'" /of 101140212 /z 0 /f "{ums} {hh}:{nn}:{ss}.{fff}"

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

Re: getTimestamp.bat for time and date processing

#44 Post by dbenham » 06 Aug 2016 10:22

If you read the documentation, you will see that the /Z option should not be used with any of {UMS}, {US}, {USD}, etc. I believe it actually works if the /Z (timezone offset in minutes) is 0, but a better alternative is to use the /U option.

All you need is {UH} to get the number of whole hours (no rollover at 24). Note that it does not pad to a specific width because there is no limit to how many digits might be required.

Code: Select all

call getTimestamp /d "'1/1/1970 01:32:21 UTC'" /of 101140212 /u /f "{ums} {uh}:{nn}:{ss}.{fff}"


I'm not sure what strange effect you are referring to. You will have to give me a specific example, describing what you expect vs. what you see.


Dave Benham

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: getTimestamp.bat for time and date processing

#45 Post by foxidrive » 06 Aug 2016 15:42

dbenham wrote:If you read the documentation, you will see that the /Z option should not be used with any of {UMS}, {US}, {USD}, etc. I believe it actually works if the /Z (timezone offset in minutes) is 0, but a better alternative is to use the /U option.

All you need is {UH} to get the number of whole hours (no rollover at 24). Note that it does not pad to a specific width because there is no limit to how many digits might be required.

Code: Select all

call getTimestamp /d "'1/1/1970 01:32:21 UTC'" /of 101140212 /u /f "{ums} {uh}:{nn}:{ss}.{fff}"



Thanks Dave, that's spot on and I'm able to remove all the kludgey code I was trying to make work.


I'm finding sustained concentration a bit challenging at the moment due to illness.

The odd lines are shown below with the code from my question - they disappeared with your fix.

10312606 02:51:52.606
15859016 04:24:19.016
21378330 05:56:18.330
26566286 07:22:46.286
26881664 07:28:01.664
34870710 09:41:10.710
40311742 11:11:51.742
45941543 12:45:41.543
51317272 14:15:17.272
56755818 15:45:55.818
62254225 17:17:34.225
67567663 18:46:07.663
67839984 18:50:39.984

77102913 21:25:02.913
81750040 22:42:30.040
82160017 22:49:20.017

90202354 01:03:22.354
95664859 02:34:24.859
100994107 04:03:14.107
106681212 05:38:01.212

Post Reply