How to create a Date object and subtract days from...
# javascript
a
How to create a Date object and subtract days from it? In JS, the accepted solution is:
Copy code
var d = new Date();
 d.setDate(d.getDate()-5);
But the Kotlin JS Date object does not expose setDate ...
l
You could use dynamic:
Copy code
var d = new Date()
d.asDynamic().setDate(d.getDate()-5)
Probably better to write an extension function for Date
Copy code
fun main() {
    val date = Date()
    date.setDate(4)
}

fun Date.setDate(date: Int){
    this.asDynamic().setDate(date)
}
a
works! Thx a lot 🙂
l
Should probably report the issue on https://youtrack.jetbrains.com though, since the set functions are part of Date.
i
We have intentionally avoided providing mutating methods on Date.
t
why?
i
We believe having a mutable date is not a good approach for working with dates. So we avoid promoting this way in Kotlin/JS. Though the workaround is easy when absolutely required.
t
while this is true do you really think you should do this dicission when the api is actually not under your control? 😕
i
The way we expose
Date
in
kotlin.js
package is definitely under our control. It's the same thing as with js Math API, for example: currently we're deprecating it in favor of
kotlin.math
package.
c
I have found (but have not yet used) a cross platform date library that looks really good... https://korlibs.soywiz.com/klock/ (there are also a few other interesting things on that site...)
❤️ 1