4

I am totally new to javascript and I have a very easy to answer question: How do I use a current year string?

Should I look like this?

var currentyear = now.getYear();

And then I want to use that string in the following code snippet (The string should always replace the 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);

Does it has to be like this?

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

2 Answers 2

11

You can get the year like this:

var yr = new Date().getFullYear();

then use the + (string concatenation) operator to join it to another string:

drawDayEvents(yr + "-12-27", "#day1");
Sign up to request clarification or add additional context in comments.

Comments

5

You should use getFullYear() instead because getYear() will return the year minus 1900.

var currentyear = now.getFullYear();

In this line:

drawDayEvents('$currentyear-12-27', '#day1');

JavaScript can't interpolate variables like PHP can. You need to concat the strings.

drawDayEvents(currentyear+'-12-27', '#day1');

Variables in JavaScript don't need to be prefixed with $ (they can contain a $ if you want).

var start = new Date(currentyear, 12-1, 27);
var end = new Date(currentyear, 12-1, 31);
if((time < start) || (time > end)) {
  time.setYear(currentyear);
}

Docs for JavaScript Date: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

14 Comments

var currentyear = now.getFullYear(); ? is $currentyear right or not?
now isn't a keyword either.
time is not declared, either. Suppose that and now should be clarified.
@MichealPerr: No, $currentyear is not right. It's just currentyear, you don't need the $.
@JaredFarrish: I'm assuming that time and now were declared earler.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.