I’ve made a tix clock in javascript over my winter break. It hasn’t been released yet but it might be coming soon. In order to make it work for my local time since I don’t use 24-hour time like Europe does (I’m guessing, I don’t actually know), I had to use special logic to convert it to 12-hour time. While for my simple clock it was easy, in other cases which require more complex manipulation, I found a great library.
Datejs is what I found. It greatly simplifies date and time manipulation and also adds many features that the Date class in native javascript should have to begin with. For example, with Datejs, you could do the following. (Taken from the examples on the front page, no less.)
// Add 3 days to Today Date.today().add(3).days();
Of course what I wanted was some code to handle hours and AM/PM. I looked through Datejs to find it but it’s there too!
var d = new Date(); var hours = d.get12HourHour(); // would be in 12-hour time rather than 24
That’s exactly what I had wanted. Though there was a problem with it. Datejs has it’s own little classing system and I don’t know how well it’ll play with Mootools. (Since Mootools does not have friends.)
So what I did was use Mootools to implement some of the functions in Datejs and add them to the Date class. I know there is a reason you don’t mess with the natives. But Mootools does it all the time. At this point, there is no reason I should constrain myself with broken rules (right?).
Date.implement({
clearTime: function() {
this.setHours(0);
this.setMinutes(0);
this.setSeconds(0);
this.setMilliseconds(0);
return this;
},
today: function() {
return this.clearTime();
},
get12HourHour: function() {
return (this.getHours() > 12) ? this.getHours() - 12 : (this.getHours() === 0) ? 12 : this.getHours();
},
get24HourHour: function() {
return this.getHours();
},
getDesignator: function() {
return (this.getHours() < 12) ? "am": "pm";
},
"info": "from datejs.com mit license"
});
My little implementation on to Date isn’t much to awe about but it still makes my life easier. Plus, I can always continue to incorporate Datejs. I remember someone telling about a Mootools plugin that did all of this already, but I can’t seem to find it anymore. If anyone knows about that plugin, let me know.
You might also consider Date.js – a MooTools Native implementation of Date:
http://www.clientcide.com/wiki/cnet-libraries/03-native/00-date
http://www.clientcide.com/wiki/cnet-libraries/03-native/01-date.extras
That’s exactly what I was looking for! I knew I had seen something like that and I asked in the IRC room but no one remembered either.
Great post. I am only now learning about Mootools. I have some catching up to do. ;)