1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
<link rel="import" href="../polymer/polymer.html">
<script src="../moment/min/moment.min.js"></script>
<script src="../moment-timezone/builds/moment-timezone-with-data.min.js"></script>
<dom-module id="chops-timestamp">
<template>
<style>
</style>
<template is="dom-if" if="[[!short]]">
[[_formattedDate]] ([[_computeRelativeTime(_date)]])
</template>
<template is="dom-if" if="[[short]]" title="[[_formattedDate]]">
[[_computeRelativeTime(_date)]]
</template>
</template>
<script>
'use strict';
/**
* `<chops-timestamp>` displays a formatted time string in PDT and the relative time.
*
* This element shows a time in a human readable form.
*
* @customElement
* @polymer
* @demo /demo/chops-timestamp_demo.html
*/
class ChopsTimestamp extends Polymer.Element {
static get is() { return 'chops-timestamp'; }
static get properties() {
return {
/** The data for the time which can be in any format readable by
* Date.parse.
*/
timestamp: String,
/** When true, a shorter version of the date will be displayed. */
short: {
type: Boolean,
value: false,
},
/** The format of the date. */
dateFormat: {
type: String,
value: "ddd, D MMM YYYY, h:mm a z",
},
/** The moment object, which is stored in UTC, to be processed. */
_date: {
type: Object,
value: () => (moment()),
computed: '_computeDate(timestamp)',
},
/** The formatted date. */
_formattedDate: {
type: String,
computed: '_computeDisplayedTime(_date, dateFormat)',
},
}
}
_computeDate(timestamp) {
// Check if timestamp is unix time first.
let date = Number.parseInt(timestamp);
if (Number.isNaN(date)) {
// Date.parse returns milliseconds since epoch but we want seconds.
date = Date.parse(timestamp) / 1000;
if (Number.isNaN(date)) {
// Default to now if all else fails.
date = (new Date()).getTime() / 1000;
}
}
return moment.unix(date).tz('America/Los_Angeles');
}
_computeDisplayedTime(date, format) {
return date.format(format);
}
_computeRelativeTime(date) {
return date.fromNow();
}
}
customElements.define(ChopsTimestamp.is, ChopsTimestamp);
</script>
<dom-module>
|