Alternative solution
This commit is contained in:
parent
aeabf4bf9b
commit
13be80afb9
1 changed files with 31 additions and 0 deletions
|
@ -43,3 +43,34 @@ alert( formatDate(new Date(new Date - 5 * 60 * 1000)) ); // "5 min. ago"
|
|||
// yesterday's date like 31.12.2016, 20:00
|
||||
alert( formatDate(new Date(new Date - 86400 * 1000)) );
|
||||
```
|
||||
|
||||
Alternative solution:
|
||||
|
||||
```js run
|
||||
function formatDate(date) {
|
||||
let dayOfMonth = date.getDate();
|
||||
let month = date.getMonth() + 1;
|
||||
let year = date.getFullYear();
|
||||
let hour = date.getHours();
|
||||
let minutes = date.getMinutes();
|
||||
let diffMs = new Date() - date;
|
||||
let diffSec = Math.round(diffMs / 1000);
|
||||
let diffMin = diffSec / 60;
|
||||
let diffHour = diffMin / 60;
|
||||
|
||||
// formatting
|
||||
year = year.toString().slice(-2);
|
||||
month = month < 10 ? '0' + month : month;
|
||||
dayOfMonth = dayOfMonth < 10 ? '0' + dayOfMonth : dayOfMonth;
|
||||
|
||||
if (diffSec < 1) {
|
||||
return 'right now';
|
||||
} else if (diffMin < 1) {
|
||||
return `${diffSec} sec. ago`
|
||||
} else if (diffHour < 1) {
|
||||
return `${diffMin} min. ago`
|
||||
} else {
|
||||
return `${dayOfMonth}.${month}.${year} ${hour}:${minutes}`
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue