显示具有类名的每个div的日期变量

时间:2016-09-21 20:54:59

标签: javascript jquery html

更新:以下代码用于显示从今天起7天和14天的日期。我们如何缩短产量以显示月份和日期(9月21日)?

如何在页面上显示每个类名的日期(innerHTML)?



var date = new Date,
  firstDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 7),
  next = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 14),
  months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec"
  ];

$('.first-date').html(function(_, val) {
 return val + firstDate;
});
$('.second-date').html(function(_, val) {
 return val + next;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span class="first-date"></span> - <span class="second-date"></span>
<br/><br/>
<span class="first-date"></span> - <span class="second-date"></span>
&#13;
&#13;
&#13;

JSFiddle:https://jsfiddle.net/dzb2okv3/1/

1 个答案:

答案 0 :(得分:0)

你可以试试这个

var  months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
    "Oct", "Nov", "Dec"];
var dateObj = new Date();
var dateObj_7 = new Date(dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate() + 7 );
var dateObj_14 = new Date(dateObj.getFullYear(), dateObj.getMonth(), dateObj.getDate() + 14 );
var month_7 = dateObj_7.getMonth(); //months from 1-12
var month_14 = dateObj_14.getMonth();
var day_7 = dateObj_7.getDate();
var day_14 = dateObj_14.getDate();
var next_7_date =  months[month_7] + " " + day_7;
var next_14_date =  months[month_14] + " " + day_14;

$('.first-date').html( next_7_date);
$('.second-date').html( next_14_date);

// if you want to get day in 2 digits (01, 02, 03 ...etc)
/*
var day_7 = ("0" + dateObj_7.getDate()).slice(-2);
var day_14 = ("0" + dateObj_14.getDate()).slice(-2);
*/

Demo