Rails' time extensions ported to JavaScript
I’ve ported Rails’ Numeric Time extensions to JavaScript since I needed to do some date calculations for a project I’m working on. Now one should be able to calculate dates in JS like this:
(5).seconds() // => 5000
(2).weeks() + (2).hours() + (15).seconds() // => 1216815000
(1).week().fromNow().toDate() // => Fri Sep 22 2006 19:16:32 GMT+0200 (CEST)
var date = new Date(2000, 11, 18, 18, 15, 23);
(2).years().since(date).toDate() // => Thu Dec 19 2002 06:15:23 GMT+0100 (CET)
Thought it could be useful for others as well. You’ll need the latest prototype library, unit tests are included.
Download a zip with both .js file and unit tests or just the .js-file.
Fri 15/9/06, 22:59
Cool stuff :-)
Why would you use (5).seconds() and not 5.seconds()?
/
Sat 16/9/06, 04:07
For some reason JavaScript needs the paranthesis to treat it as a number. It’s the same thing with functions, (function() {…}).myMethod() needs the parantheses as well. Strings and dates seems to do fine without thought. I don’t know the exact reason why this is the way JS handles the data types.
/
Sat 16/9/06, 10:54
Aaaah, it is quite logical actually when you keep in mind that there are floats in Javascript :-)
“123.” is a valid number. “123.foo()” will parse as “123.” and then complain about a missing “;” before the next statement.
/
Sat 16/9/06, 12:54
Ah, yes, that must be the reason. Thanks for sorting that out :)
/
Tue 19/9/06, 12:40
Thanks for the functions! They will come in very handy for some Indesign javascript work I’m doing..
Hmm I wonder if the prototype libraries will work in indesign though.. We’ll see!
/
Wed 20/9/06, 14:26
@ Jonathan: Remember to copy Prototype’s Object.extend method as well or replace my functions so they look like:
Number.prototype.days = function() {…}
etc
/
Sun 24/9/06, 14:01
I replaced the functions as you said, and it works perfectly.. Thanks for this, it’ll come in very handy!
/
Mon 2/10/06, 17:58
Great work, Martin. Feel free to submit this as a patch to Prototype.
/
Tue 3/10/06, 13:00
Andrew: It’s now submitted as a patch. (Ticket #6342)
/
Mon 23/10/06, 19:05
i dont know about his.
/
Wed 8/11/06, 09:24
Hello Martin,
I found your name on the scriptaculous site, and I am wondering if some of you may be interested in a small project.
I have posted some details: http://web.mac.com/marvinzai/iWeb/Site/script.html
Please let me know if you can do this and if you are available.
Thanks,
Marvin
/
Mon 5/3/07, 10:18
Totally awesome! Thank you for sharing this. Just the thing i was looking for.
/
Mon 26/11/07, 15:37
scripta.culo.us isn’t realy required. You should remove that dependency from the website ;)
Besides that, very cool extension!
/
Mon 26/11/07, 19:42
puRe: You are right, thanks
/