加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

Windows命令“date%s”的等价物是什么

发布时间:2020-12-14 02:14:00 所属栏目:Windows 来源:网络整理
导读:我正在写一个批处理脚本,我需要unix时间.这在 linux下很容易,但我无法弄清楚如何在windows中执行此操作. 解决方法 这是一个本地批处理解决方案,应该适用于任何语言环境.它使用WMIC以与语言环境无关的方式获取当前本地时间.其他一切都是字符串解析和基本数学
我正在写一个批处理脚本,我需要unix时间.这在 linux下很容易,但我无法弄清楚如何在windows中执行此操作.

解决方法

这是一个本地批处理解决方案,应该适用于任何语言环境.它使用WMIC以与语言环境无关的方式获取当前本地时间.其他一切都是字符串解析和基本数学的“简单”问题.

:UnixTime  [ReturnVar]  [TimeStamp]
::
:: Computes the Unix time from the current local time as reported by the
:: operating system. The Unix time is the number of seconds that have elapsed
:: since midnight Coordinated Universal Time (UTC),January 1,1970,not
:: counting leap seconds.
::
:: The result is returned in variable ReturnVar,:: or the result is echoed if ReturnVar is not specified
::
:: If the TimeStamp is provided in the 2nd parameter,then the Unix time for
:: the TimeStamp is computed,rather then for the current time.
::
:: The TimeStamp must have the same format as used by WMIC:
::
::   YYYYMMDDhhmmss.ffffffSzzz
::
:: where:
::
::   YYYY   = gregorian year
::   MM     = month
::   DD     = day
::   hh     = hour in 24 hour format
::   mm     = minute
::   ss     = seconds
::   ffffff = fractional seconds (microseconds)
::   S      = timezone sign: + or -
::   zzz    = timezone: minutes difference from GMT
::
:: Each component must be zero prefixed as needed to maintain the proper width.
::
:: The ReturnVar parameter must be provided in order to use the TimeStamp.
:: A ReturnVar of "" will function the same as no ReturnVar. This enables the
:: specification of a TimeStamp without an actual ReturnVar.
::
@echo off
setlocal
set "ts=%~2"
if not defined ts for /f "skip=1 delims=" %%A in ('wmic os get localdatetime') do if not defined ts set "ts=%%A"
set /a "yy=10000%ts:~0,4% %% 10000,mm=100%ts:~4,2% %% 100,dd=100%ts:~6,2% %% 100"
set /a "dd=dd-2472663+1461*(yy+4800+(mm-14)/12)/4+367*(mm-2-(mm-14)/12*12)/12-3*((yy+4900+(mm-14)/12)/100)/4"
set /a ss=(((1%ts:~8,2%*60)+1%ts:~10,2%)*60)+1%ts:~12,2%-366100-%ts:~21,1%((1%ts:~22,3%*60)-60000)
set /a ss+=dd*86400
endlocal & if "%~1" neq "" (set %~1=%ss%) else echo %ss%
exit /b

请注意,此解决方案的使用寿命有限.当Unix时间超过有符号32位整数的最大值时,它将在2038-01-19停止工作.

编辑 – 已编辑代码以支持在命令行上转换时间戳字符串而不是当前本地时间.支持的精确时间范围是1901-12-13 20:45:52.000000到2038-01-19 03:14:07.999999 GMT. 1970-01-01 00:00:00.000000之前的时间将产生负值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读