如何使用div在javascript中显示当前月份,年份

Dig*_*ite 3 javascript jquery datetime date

我正在尝试获取一个jquery或java-script代码,用于在div中显示当前月份和年份,但到目前为止还无法使用.我的意思是我想以这种格式显示当前的月份和年份:October 2012这样每个月我都不需要编辑它或任何东西.

我在这里看到了很多问题,但没有一个显示如何在div中显示变量.

知道怎么做到这一点?

非常感谢您的帮助和想法

Ble*_*der 15

JavaScript本身并没有实现strftime,所以你必须做一些不那么优雅的事情:

window.onload = function() {
    var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];;
    var date = new Date();

    document.getElementById('date').innerHTML = months[date.getMonth()] + ' ' + date.getFullYear();
};
Run Code Online (Sandbox Code Playgroud)

我假设你有一个元素iddateHTML中的某个地方.


Fos*_*erZ 9

在javascript中没有inbuild函数来获取月份的全名.您可以创建一个月份名称数组,并使用它来获取完整的月份名称,例如

var m_names = ['January', 'February', 'March', 
               'April', 'May', 'June', 'July', 
               'August', 'September', 'October', 'November', 'December'];

d = new Date();
var n = m_names[d.getMonth()]; 
Run Code Online (Sandbox Code Playgroud)


Par*_*ani 7

获取当前日期、月份、年份或 ETC....

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)
Run Code Online (Sandbox Code Playgroud)