Skip to content

Commit 13be80a

Browse files
authored
Alternative solution
1 parent aeabf4b commit 13be80a

File tree

1 file changed

+31
-0
lines changed
  • 1-js/05-data-types/10-date/8-format-date-relative

1 file changed

+31
-0
lines changed

1-js/05-data-types/10-date/8-format-date-relative/solution.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,34 @@ alert( formatDate(new Date(new Date - 5 * 60 * 1000)) ); // "5 min. ago"
4343
// yesterday's date like 31.12.2016, 20:00
4444
alert( formatDate(new Date(new Date - 86400 * 1000)) );
4545
```
46+
47+
Alternative solution:
48+
49+
```js run
50+
function formatDate(date) {
51+
let dayOfMonth = date.getDate();
52+
let month = date.getMonth() + 1;
53+
let year = date.getFullYear();
54+
let hour = date.getHours();
55+
let minutes = date.getMinutes();
56+
let diffMs = new Date() - date;
57+
let diffSec = Math.round(diffMs / 1000);
58+
let diffMin = diffSec / 60;
59+
let diffHour = diffMin / 60;
60+
61+
// formatting
62+
year = year.toString().slice(-2);
63+
month = month < 10 ? '0' + month : month;
64+
dayOfMonth = dayOfMonth < 10 ? '0' + dayOfMonth : dayOfMonth;
65+
66+
if (diffSec < 1) {
67+
return 'right now';
68+
} else if (diffMin < 1) {
69+
return `${diffSec} sec. ago`
70+
} else if (diffHour < 1) {
71+
return `${diffMin} min. ago`
72+
} else {
73+
return `${dayOfMonth}.${month}.${year} ${hour}:${minutes}`
74+
}
75+
}
76+
```

0 commit comments

Comments
 (0)