js 获取当前时间,js 获取当前时间3个月前日期
发布时间:2024-06-11 13:11:06 商业分析
在前端开发中,经常需要获取当前时间或者根据当前时间计算出一段时间之前的日期。下面将介绍如何使用JavaScript来获取当前时间以及获取当前时间三个月前的日期。
1. 获取当前时间
要获取当前时间,可以使用JavaScript中的Date对象来实现。以下是获取当前时间的代码:
示例:
var now = new Date()
var year = now.getFullYear()
var month = now.getMonth() + 1
var day = now.getDate()
console.log(year + "-" + month + "-" + day)
通过以上代码,可以得到当前的年、月、日信息,并以指定格式输出。
2. 获取当前时间三个月前的日期
下面介绍如何使用JavaScript获取当前时间三个月前的日期:
方法一:
var now = new Date()
now.setMonth(now.getMonth() 3)
var year = now.getFullYear()
var month = now.getMonth() + 1
var day = now.getDate()
console.log(year + "-" + month + "-" + day)
通过这段代码,可以得到当前时间三个月前的日期,并以指定格式输出。
方法二:
var now = new Date()
var year = now.getFullYear()
var month = now.getMonth() + 1
var day = now.getDate()
if (month