Skip to content
jiangbai333@163.com edited this page Nov 25, 2016 · 3 revisions

format 方法接收一个String类型int类型实参,当接收int类型时将会在内部构建一个当前时间戳+参数对应小时数Date()对象或对应该传入时间戳的Date()对象,而String类型则会根据语义构建相应的Date()对象。

int类型可选值为任意整数,例如:1,-1,10等等,但会根据传入参数的长度,做出不同的解析:

  • 1~9位数 当前时间戳+参数对应小时数
  • 10位数 针对接口返回的10位时间戳进行解析
  • 13位数 针对原生javascript的13位时间戳进行解析

String类型可选值为:

  • start 与当前时间对应的当天起始时间
  • end 与当前时间对应的当天截至时间
  • Nmonth 与当前时间相差时间间隔为Nmonth的时间(N为任意整数)
  • Nyear 与当前时间相差时间间隔为Nyear的时间(N为任意整数)
  • 其它 当前时间

字面量参数:

  • Y 返回4位长度的年
  • y 返回2位长度的年
  • M 返回月
  • D 返回日
  • H 返回小时
  • F 返回分钟
  • S 返回秒
  • ms 返回微秒
  • long-stamp 返回13位时间戳
  • short-stamp 返回10位时间戳

利用 format 获取格式化的时间字符串

字面量(Y、M、D、H、F、S、ms)转义
"Y/M/D".format(); //"2016/11/23"
"H:F:S".format(); //"11:18:55"
"Y/M/D H:F:S .ms".format(); //"2016/11/23 11:18:55 .401"
"Y年M月D日".format(); //"2016年11月23日"
"H时F分S秒 ms微秒".format(); //"11时18分55秒 401微秒"
"Y年M月D日 H:F:S .ms".format(); //"2016年11月23日 11:18:55 .401"

"long-stamp".format(); //1479889135401
"short-stamp".format(); //1479889135
1~9位int类型参数 代表要获取的时间与当前时间小时数的时间间隔
"Y年M月D日 H:F:S .ms".format(5); //"2016年11月23日 16:18:55 .401"
"Y年M月D日 H:F:S .ms".format(-5); //"2016年11月23日 06:18:55 .401"
10、13位int类型参数 代表要获取的时间的时间戳
"Y年M月D日 H:F:S .ms".format(1479889135); //"2016年11月23日 06:18:55 .0"
"Y年M月D日 H:F:S .ms".format(1479889135401); //"2016年11月23日 06:18:55 .401"
获取当天的开始时间、截至时间
"Y年M月D日 H:F:S .ms".format("start"); //"2016年11月23日 00:00:00 .0"
"Y年M月D日 H:F:S .ms".format("end"); //"2016年11月23日 23:59:59 .999"
Nmonth参数代表要获取的时间与当前时间月份的时间间隔
"Y年M月D日 H:F:S .ms".format("5month"); //"2017年4月23日 11:18:55 .401"
"Y年M月D日 H:F:S .ms".format("-5month"); //"2016年6月23日 11:18:55 .401"
Nyear参数代表要获取的时间与当前时间年份的时间间隔
"Y年M月D日 H:F:S .ms".format("5year"); //"2021年11月23日 11:18:55 .401"
"Y年M月D日 H:F:S .ms".format("-5year"); //"2011年11月23日 11:18:55 .401"