~macslow/unity8/fix-1475678

« back to all changes in this revision

Viewing changes to Components/Time.js

  • Committer: Michał Sawicz
  • Date: 2013-06-05 22:03:08 UTC
  • Revision ID: michal.sawicz@canonical.com-20130605220308-yny8fv3futtr04fg
Inital unity8 commit.

Previous history can be found at https://code.launchpad.net/~unity-team/unity/phablet

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * Copyright (C) 2013 Canonical, Ltd.
 
3
 *
 
4
 * This program is free software; you can redistribute it and/or modify
 
5
 * it under the terms of the GNU General Public License as published by
 
6
 * the Free Software Foundation; version 3.
 
7
 *
 
8
 * This program is distributed in the hope that it will be useful,
 
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
 * GNU General Public License for more details.
 
12
 *
 
13
 * You should have received a copy of the GNU General Public License
 
14
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
15
 */
 
16
 
 
17
.pragma library
 
18
 
 
19
var factors = {
 
20
    "second": [ 1000, "a second ago", "in a second", "%1 seconds ago", "in %1 seconds" ],
 
21
    "minute": [ 60, "a minute ago", "in a minute", "%1 minutes ago", "in %1 minutes" ],
 
22
    "hour":   [ 60, "an hour ago", "in an hour", "%1 hours ago", "in %1 hours" ],
 
23
    "day":    [ 24, "yesterday", "tomorrow", "%1 days ago", "in %1 days" ],
 
24
    "week":   [ 7, "a week ago", "in a week", "about %1 weeks ago", "in about %1 weeks" ],
 
25
    "month":  [ 4.35, "a month ago", "in a month", "%1 months ago", "in %1 months" ], // == 365.25 days / 12 months / 7 days
 
26
    "year":   [ 12, "a year ago", "in a year", "%1 years ago", "in %1 years" ]
 
27
}
 
28
 
 
29
function readableFromNow(date, now) {
 
30
    var then = new Date(date);
 
31
    if (isNaN(then)) return "";
 
32
    if (now === undefined) {
 
33
        now = new Date();
 
34
    } else if (isNaN(now)) throw "now is NaN";
 
35
    var diff = Math.abs(now - then);
 
36
    if (diff < 1000) return "just now";
 
37
 
 
38
    var future = now < then;
 
39
    var humanDiff;
 
40
    for (var k in factors) {
 
41
        diff /= factors[k][0];
 
42
        if (Math.floor(diff) == 1) {
 
43
            humanDiff = factors[k][future ? 2 : 1];
 
44
        } else if (Math.floor(diff) > 1) {
 
45
            humanDiff = factors[k][future ? 4 : 3].arg(Math.round(diff));
 
46
        } else break;
 
47
    }
 
48
    return humanDiff;
 
49
}