在 html/javascript 中显示 "years of service" 的简单方法
Simple way to display "years of service" in html/javascript
我想在网站上显示服务年限的数字。基本上我认为我可以输入开始日期和当前日期以获得介于两者之间的年份的输出。
我可以使用以下代码来计算当前年份,但不确定如何计算差异
document.write(2010) + (/\d{4}/.exec(Date())[0])
只需从当前年份中减去 2010
并连接字符串:
document.write((/\d{4}/.exec(Date())[0]) - 2010 + ' years of service')
尽管获取年份的更简单方法是使用 Date.getFullYear()
:
document.write(new Date().getFullYear() - 2010 + ' years of service')
您可以使用 Date
函数来提取时间的组成部分。
要获得年份,您可以使用类似的东西:
today = new Date();
year = today.getFullYear();
计算年份之间的差异(year
值为数字):
d = year - 2010;
你可以这样
document.write(new Date().getFullYear() - 2010)
document.write(新日期().getFullYear() - 2010)
我想在网站上显示服务年限的数字。基本上我认为我可以输入开始日期和当前日期以获得介于两者之间的年份的输出。
我可以使用以下代码来计算当前年份,但不确定如何计算差异
document.write(2010) + (/\d{4}/.exec(Date())[0])
只需从当前年份中减去 2010
并连接字符串:
document.write((/\d{4}/.exec(Date())[0]) - 2010 + ' years of service')
尽管获取年份的更简单方法是使用 Date.getFullYear()
:
document.write(new Date().getFullYear() - 2010 + ' years of service')
您可以使用 Date
函数来提取时间的组成部分。
要获得年份,您可以使用类似的东西:
today = new Date();
year = today.getFullYear();
计算年份之间的差异(year
值为数字):
d = year - 2010;
你可以这样
document.write(new Date().getFullYear() - 2010)
document.write(新日期().getFullYear() - 2010)