首页 > 解决方案 > 如何在os x中将日期的字符串格式转换为毫秒?

问题描述

我想2020-01-17T07:41:53.000Z在 os X 中更改为毫秒格式。

如何实现?

标签: bashmacos

解决方案


在 Mac OS 下转换日期

date '2020-01-17T07:41:53.000Z'
date: illegal time format
usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
            [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

然后,从man date

 -j      Do not try to set the date.  This allows you to use the -f flag
         in addition to the + option to convert one date format to
         another.

重组$str

str="2020-01-17T07:41:53.000Z"
IFS='-T:.Z' read _ccyy _mm _dd _HH _MM _ss _mil <<<"$str"
date -j +%c $_mm$_dd$_HH$_MM$_ccyy.$_ss
Fri Jan 17 07:41:53 2020

看起来工作正常!

epoch=$(env TZ=UTC date -j +%s $_mm$_dd$_HH$_MM$_ccyy.$_ss)
printf -v milliseconds "%s%03.0f" $epoch $milli

echo $milliseconds
1579246913000

...而且只是:关心TZ


推荐阅读