6

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

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

知道如何实现吗?

非常感谢您的帮助和想法

4

7 回答 7

20

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();
};

我假设您的 HTML 中有一个带有idof的元素。date

于 2012-10-06T08:00:42.213 回答
11

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

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

d = new Date();
var n = m_names[d.getMonth()]; 
于 2012-10-06T08:01:58.340 回答
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)
于 2016-09-05T06:33:09.440 回答
5

看看 moment() http://momentjs.com

moment().format('MMMM YYYY');
于 2012-10-06T08:01:14.277 回答
2

使用它,您可以获得唯一的当前月份

var d = new Date();
var n = d.getMonth()+1;

n 的值为 3(如当前月份是三月)

于 2017-03-24T19:40:04.320 回答
1
var dt = new Date();
var m = ['January','February', 'March', ...][dt.getMonth()]; //you get the idea...
var y = dt.getFullYear();
$('<div>').html(m + " " + y).appendTo(document);
于 2012-10-06T08:01:16.687 回答
1

您可以使用 JqueryUI 格式化您的日期(如果您已经使用它)。Datepicker 提供格式:

$.datepicker.formatDate("MM yy", date);

要在 div 中插入日期,您可以使用此功能:

$("#divId").append($.datepicker.formatDate("MM yy", new Date()));

来源:http ://docs.jquery.com/UI/Datepicker/formatDate

于 2012-10-06T08:06:18.613 回答