Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this JavaScript statement calculate the date?

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?

like image 435
Bob Dylan Avatar asked Jul 08 '10 07:07

Bob Dylan


1 Answers

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).

like image 140
James Avatar answered Sep 20 '22 00:09

James