Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.97 KB | None | 0 0
  1. const MONTH_NAMES = [
  2. 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho',
  3. 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro',
  4. ];
  5.  
  6.  
  7. function getFormattedDate(date, prefomattedDate = false, hideYear = false) {
  8. const day = date.getDate();
  9. const month = MONTH_NAMES[date.getMonth()];
  10. const year = date.getFullYear();
  11. const hours = date.getHours();
  12. let minutes = date.getMinutes();
  13.  
  14. if (minutes < 10) {
  15. // Adding leading zero to minutes
  16. minutes = `0${minutes}`;
  17. }
  18.  
  19. if (prefomattedDate) {
  20. // Today at 10:20
  21. // Yesterday at 10:20
  22. return `${prefomattedDate} às ${hours}:${minutes}`;
  23. }
  24.  
  25. if (hideYear) {
  26. // 10. January at 10:20
  27. return `${day}. ${month} às ${hours}:${minutes}`;
  28. }
  29.  
  30. // 10. January 2017. at 10:20
  31. return `${day}. ${month} ${year}. às ${hours}:${minutes}`;
  32. }
  33.  
  34.  
  35. // --- Main function
  36. function timeAgo(dateParam) {
  37. if (!dateParam) {
  38. return null;
  39. }
  40.  
  41. const date = typeof dateParam === 'object' ? dateParam : new Date(dateParam);
  42. const DAY_IN_MS = 86400000; // 24 * 60 * 60 * 1000
  43. const today = new Date();
  44. const yesterday = new Date(today - DAY_IN_MS);
  45. const seconds = Math.round((today - date) / 1000);
  46. const minutes = Math.round(seconds / 60);
  47. const isToday = today.toDateString() === date.toDateString();
  48. const isYesterday = yesterday.toDateString() === date.toDateString();
  49. const isThisYear = today.getFullYear() === date.getFullYear();
  50.  
  51.  
  52. if (seconds < 5) {
  53. return 'agora';
  54. } if (seconds < 60) {
  55. return `${seconds} segundos atrás`;
  56. } if (seconds < 90) {
  57. return 'cerca de um minuto atrás';
  58. } if (minutes < 60) {
  59. return `${minutes} minutos atrás`;
  60. } if (isToday) {
  61. return getFormattedDate(date, 'Hoje'); // Today at 10:20
  62. } if (isYesterday) {
  63. return getFormattedDate(date, 'Ontem'); // Yesterday at 10:20
  64. } if (isThisYear) {
  65. return getFormattedDate(date, false, true); // 10. January at 10:20
  66. }
  67.  
  68. return getFormattedDate(date); // 10. January 2017. at 10:20
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement