Home > Article > Web Front-end > js gets the time several days before the current time
In languages such as C, a few days before the current time is normally obtained, we often have to consider the logical judgment of many situations such as "Is this year a good year? Is the month February?" In JavaScript, these logics can be omitted. The implementation method is introduced below.
1. First introduce a few functions
getTime(): Returns the number of milliseconds from January 1, 1970 to the present.
setTime(): Set Date object in milliseconds.
getDate(): Returns the day of the month (1 ~ 31) from the Date object.
getMonth(): Returns the month (0 ~ 11) from the Date object.
getFullYear(): Returns the year as a four-digit number from a Date object.
2. Implementation
Idea: First, get the number of milliseconds (from January 1, 1970 to the present) through getTime(); then we use the obtained milliseconds Subtract the number of milliseconds in a day (or several days) from the number, then submit the result to setTime() for processing, and then use getDate(), getMonth(), getFullYear() and other methods to obtain the day, month, and year. (Here we get the two days before the current time)
Code:
var now = new Date();var TwoDaysAgo = new Date();//获取当前时间的毫秒数var nowMilliSeconds = now.getTime();//用获取毫秒数 减去两天的毫秒数 赋值给TwoDaysAgo对象(一天有86400000毫秒)TwoDaysAgo.setTime(nowMilliSeconds-(2*86400000));//通过赋值后的TwoDaysAgo对象来得到 两天前的 年月日。这里我们将日期格式化为20180301的样子。//格式化日,如果小于9,前面补0 var day = ("0" + TwoDaysAgo.getDate()).slice(-2); //格式化月,如果小于9,前面补0 var month = ("0" + (TwoDaysAgo.getMonth() + 1)).slice(-2); //拼装完整日期格式 var getToday = TwoDaysAgo.getFullYear()+(month)+(day); alert(getToday); //20180227
For more related tutorials, please visit JavaScript video tutorial