我是javascript的新手,我有一个非常容易回答的问题:如何使用当前年份的字符串?
我应该这样吗?
var currentyear = now.getYear();
然后我想在以下代码片段中使用该字符串(字符串应始终替换2011)
drawDayEvents('2011-12-27', '#day1');
drawDayEvents('2011-12-28', '#day2');
drawDayEvents('2011-12-29', '#day3');
drawDayEvents('2011-12-30', '#day4');
...
var start = new Date(2011, 12-1, 27);
var end = new Date(2011, 12-1, 31);
if((time < start) || (time > end)) {
time.setYear(2011);
它必须是这样吗?
var currentyear = now.getYear();
drawDayEvents('$currentyear-12-27', '#day1');
drawDayEvents('$currentyear-12-28', '#day2');
drawDayEvents('$currentyear-12-29', '#day3');
drawDayEvents('$currentyear-12-30', '#day4');
...
var start = new Date($currentyear, 12-1, 27);
var end = new Date($currentyear, 12-1, 31);
if((time < start) || (time > end)) {
time.setYear($currentyear);
答案 0 :(得分:6)
您应该使用getFullYear()
,因为getYear()
将返回年份减去1900年。
var currentyear = now.getFullYear();
在这一行:
drawDayEvents('$currentyear-12-27', '#day1');
JavaScript无法像PHP那样插入变量。你需要连接字符串。
drawDayEvents(currentyear+'-12-27', '#day1');
JavaScript中的变量不需要以$
为前缀(如果需要,他们可以包含$
。)
var start = new Date(currentyear, 12-1, 27);
var end = new Date(currentyear, 12-1, 31);
if((time < start) || (time > end)) {
time.setYear(currentyear);
}
JavaScript的文档日期:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
答案 1 :(得分:5)
你可以这样得到这样的一年:
var yr = new Date().getFullYear();
然后使用+(字符串连接)运算符将其连接到另一个字符串:
drawDayEvents(yr + "-12-27", "#day1");