views:

92

answers:

2

So I was looking at how I could display a Desktop Notification using a Google Chrome extensions when I came across these lines of code:

var time = /(..)(:..)/(Date());              // The prettyprinted time.
var hour = time[1] % 12 || 12;               // The prettyprinted hour.
var period = time[1] < 12 ? 'a.m.' : 'p.m.'; // The period of the day.

What the heck does all of this do?

+1  A: 

The first line is using a regular expression to extract the time element from the string returned by Date(). For instance, this might be '08:37' The brackets in this regular expression give two different 'groups' of characters, the first group matching '08', the second matching '37'

The second line is taking the first set of characters, which will be automatically converted to a number, and getting the remainder of division by 12. Presumably to turn a 24 hour clock number into a 12 hour clock number. '|| 12' acts to return 12 just in case the remainder is 0.

The third line uses a ternary conditional operator to add 'a.m' just in case the hour is smaller than 12, otherwise 'p.m.'

Yellowfog
+8  A: 

Fascinating, I've not seen this before:

/regex/(...);

EDIT: see this!

This:

/(..)(:..)/(Date());
// seems to emulate the functionality of exec()

Will return the match (array of matched groups) of the regular expression, /(..)(:..)/, against the string (Date()):

"Thu Jul 08 2010 09:40:38 GMT+0200 (W. Europe Daylight Time)"

(or whatever time it happens to be)

The returned array (the match), in this case, is:

["09:40", "09", ":40"]

This line:

var hour = time[1] % 12 || 12; 

...simply determines the hour. If the hour is falsey (i.e. 0) then it defaults to 12 -- this makes it possible for the next statement to return the correct am/pm suffix. (12:00 is am).

J-P
You could actually shorten the above code by replacing the first line with `var hour = /(..)(:..)/(Date())[1];` and then simply referring to `hour` instead of `time[1]`.
musicfreak