js different methods to get the current date yesterday, today, tomorrow's date

learning target:

学习目标

  • Get the current date yesterday, today, tomorrow's date

Learning Content:

内容
1. Method
1. Get the current date

  var today = new Date();  

2. Get yesterday’s date

  var yesterday = this.getDay(-1)

3. Get today’s date

   var today = this.getDay(0)

5. Get tomorrow’s date

   var tomorrow = this.getDay(1)

6. The sample code of the called method is as follows:
Get the current date yesterday, today, and tomorrow's date

methods: {
        
            getDay(day) {  
                var today = new Date();  
                var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;  
                today.setTime(targetday_milliseconds); //注意,这行是关键代码
                  
                var tYear = today.getFullYear();  
                var tMonth = today.getMonth();  
                var tDate = today.getDate();  
                tMonth = this.doHandleMonth(tMonth + 1);  
                tDate = this.doHandleMonth(tDate);  
                return tYear + "-" + tMonth + "-" + tDate;
            },
            doHandleMonth(month) {  
                var m = month;  
                if (month.toString().length == 1) {  
                    m = "0" + month;  
                }  
                return m;
            },
        },

2. Method 2

1. Get the current date

  var today = new Date();

2. Get yesterday’s date

   today .setTime(day1.getTime()-24*60*60*1000);
   var yesterday = today .getFullYear()+"-" + (today .getMonth()+1) + "-" + today .getDate();

3. Get today’s date

   today .setTime(today .getTime());
   var day= today .getFullYear()+"-" + (today .getMonth()+1) + "-" + today .getDate();

4. Get tomorrow’s date

   today .setTime(today .getTime()+24*60*60*1000);
   var tomorrow= today .getFullYear()+"-" + (today .getMonth()+1) + "-" + today .getDate();

Summarize:

知识小结:

Summarize:

  • Get the current date and calculate the desired date
  {
            text: '本月',
            onClick(picker) {
                // 获取当前日期
                const today = new Date();
                // 获取当前月份的第一天
                const start = new Date(today.getFullYear(), today.getMonth(), 1);
                // 获取当前月份的最后一天
                const end = new Date(today.getFullYear(), today.getMonth() + 1, 0);
                picker.$emit('pick', [start, end]);
            }
          },
  • 1. Call this method by passing a value
 created() {
            console.log("昨天:", this.getDay(-1))
            console.log("今天:", this.getDay(0))
            console.log("明天:", this.getDay(1))
            console.log("20年以后:", this.getDay(20 * 365))
        }
  • Get the current time, new Date()
  • day is number, getDay(-1): yesterday’s date; getDay(0): today’s date; getDay(1): tomorrow’s date;

Guess you like

Origin blog.csdn.net/YHLSunshine/article/details/132609217