I've got the following code for a jquery timer plugin. The compiler gives me the error: "Type 'number' is not assignable to type 'Date'"
$(function(){
var note = $('#note'),
ts = new Date(2012, 0, 1),
newYear = false;
if((new Date()) > ts){
ts = (new Date()).getTime() + 24*60*60*1000; //counting 24 hours
newYear = false;
}
});
});
};
I've got the following code for a jquery timer plugin. The compiler gives me the error: "Type 'number' is not assignable to type 'Date'"
$(function(){
var note = $('#note'),
ts = new Date(2012, 0, 1),
newYear = false;
if((new Date()) > ts){
ts = (new Date()).getTime() + 24*60*60*1000; //counting 24 hours
newYear = false;
}
});
});
};
Share
Improve this question
edited Sep 11, 2016 at 9:20
sepp2k
370k56 gold badges680 silver badges682 bronze badges
asked Sep 11, 2016 at 9:15
user2203633user2203633
1151 gold badge1 silver badge10 bronze badges
1
|
3 Answers
Reset to default 17You need to create a new instance of Date
:
if((new Date()) > ts){
ts = new Date((new Date()).getTime() + 24*60*60*1000);
newYear = false;
}
This way ts
is assigned with a new Date
with the given time.
Also, there's no need to create two instance of Date
for now, you can just put it in a variable an reuse it:
$(function(){
var note = $('#note'),
ts = new Date(2012, 0, 1),
newYear = false,
now = new Date();
if(now > ts){
ts = new Date(now.getTime() + 24*60*60*1000);
newYear = false;
}
});
When assigning variables in typescript it can help to assign the type explicitly to avoid any confusion.
When assigning:
ts = new Date(2012, 0, 1)
you avoided declaring what type ts was and left it up to the "compiler".
If you had tried:
var ts : number = new Date(2012, 0, 1);
for example (I know this takes up more space, sorry), you would have gotten as similar error.
To get around this, you either need a new variable for your declaration:
ts = new Date(now.getTime() + 24*60*60*1000);
Or more cleanly, you avoid declaring ts and construct:
var note = $('#note')
after you have decided what types all the values will be. Something like:
if(new Date() > (new Date(2012, 0, 1))
and decide from there how your "note" object will be formed.
let oneweek = new Date((new Date()).setDate(today.getDate() + 7));
let twoweek = new Date((new Date()).setDate(today.getDate() + 14));
let onemonth = new Date((new Date()).setDate(today.getMonth() + 1));
let threemonth = new Date((new Date()).setDate(today.getMonth() + 3));
ts = new Date(2012, 0, 1)
,ts
is a date, but ints = (new Date()).getTime() + 24*60*60*1000;
ts
is a number. May I suggest you to use momentjs to "play" with date? – user180100 Commented Sep 11, 2016 at 9:17