JavaScript 如何获得一年中的日期和月份

JavaScript 如何获得一年中的日期和月份

给定一个日期,任务是使用JavaScript获得一年中的日期和月份。

方法:

  • 首先使用 new Date() 获取当前日期。
  • 使用 getDay() 方法以数字格式获取当前日期,将其映射到星期几。
  • 使用 getMonth() 方法以数字格式获取当前月份,将其映射到月份名称。

示例1: 在这个示例中,月份和日期是根据以上方法确定的。

<body> 
  
    <h1 style="color:green;"> 
        GeeksForGeeks 
    </h1> 
  
    <p id="GFG_UP"> 
    </p> 
  
    <button onclick="GFG_Fun()"> 
        click here 
    </button> 
  
    <p id="GFG_DOWN"> 
    </p> 
  
    <script> 
        var el_up = document.getElementById("GFG_UP"); 
        var el_down = document.getElementById("GFG_DOWN"); 
          
        el_up.innerHTML = "Click on the button to get " 
                + "the day and month of the date."; 
          
        var Days = ['Sunday', 'Monday', 'Tuesday', 
                'Wednesday', 'Thursday', 'Friday', 'Saturday']; 
          
        var Months = ['January', 'February', 'March', 'April', 
                'May', 'June', 'July', 'August', 'September', 
                'October', 'November', 'December']; 
          
        var currentDay = new Date(); 
          
        // Get the current day name 
        var day = Days[currentDay.getDay()]; 
          
        // Get the current month name 
        var month = Months[currentDay.getMonth()]; 
          
        function GFG_Fun() { 
            el_down.innerHTML = "Day - " + day 
                    + ",<br> Month - " + month; 
        } 
    </script> 
</body>

输出:

JavaScript 如何获得一年中的日期和月份

示例2: 这个示例和第一个示例相同,只是采用了不同的方法。在这个示例中,月份和日期是由上面的方法确定的。

<body style = "text-align:center;"> 
      
    <h1 style = "color:green;" > 
        GeeksForGeeks 
    </h1> 
      
    <p id = "GFG_UP" style = 
        "font-size: 19px; font-weight: bold;"> 
    </p> 
      
    <button onclick = "GFG_Fun()"> 
        click here 
    </button> 
      
    <p id = "GFG_DOWN" style = 
        "color: green; font-size: 24px; font-weight: bold;"> 
    </p> 
      
    <script> 
        var el_up = document.getElementById("GFG_UP"); 
        var el_down = document.getElementById("GFG_DOWN"); 
      
        el_up.innerHTML = "Click on the button to get the " 
                    + "day and month of the date."; 
          
        var currentDay = new Date(); 
          
        // Get the current day name 
        var day = currentDay.getDay(); 
          
        // Getting the current month name 
        var month = currentDay.getMonth(); 
          
        function GFG_Fun() { 
            el_down.innerHTML = "Day - " + day + 
                    " Where, Monday is 1,<br> Month - " 
                    + month +" Where, January is 0."; 
        } 
    </script> 
</body>

输出:

JavaScript 如何获得一年中的日期和月份

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程