Last active
February 3, 2022 14:39
-
-
Save BenjamimRodrigo/cd7e00cdea8c0bbb0a3795ede22bbc0d to your computer and use it in GitHub Desktop.
Javascript function to format a date/time to relative time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function formatToHumanDateTime(datetime) { | |
if(!(datetime instanceof Date)) return "data/hora inválida"; | |
const now = Date.now() / 1000; | |
var diff = now - datetime.getTime() / 1000; | |
if (diff >= 0) { | |
var day_diff = Math.floor(diff / 86400); | |
if(day_diff === 0) | |
{ | |
if(diff < 60) return 'agorinha'; | |
if(diff < 120) return 'há um minuto'; | |
if(diff < 3600) return 'há ' + Math.floor(diff / 60) + ' minutos'; | |
if(diff < 7200) return 'há uma hora'; | |
if(diff < 86400) return 'há ' + Math.floor(diff / 3600) + ' horas'; | |
} | |
if(day_diff === 1) return 'ontem'; | |
if(day_diff < 7) return 'há ' + day_diff + ' dias'; | |
if(day_diff < 14) return 'há uma semana'; | |
if(day_diff < 31) return 'há ' + Math.ceil(day_diff / 7) + ' semanas'; | |
if(day_diff < 60) return 'mês passado'; | |
if(day_diff < 366) return 'há ' + Math.ceil(day_diff / 30) + ' meses'; | |
} else { | |
diff = Math.abs(diff); | |
day_diff = Math.floor(diff / 86400); | |
if(day_diff === 0) | |
{ | |
if(diff < 120) return 'em um minuto'; | |
if(diff < 3600) return 'em ' + Math.floor(diff / 60) + ' minutos'; | |
if(diff < 7200) return 'em uma hora'; | |
if(diff < 86400) return 'em ' + Math.floor(diff / 3600) + ' horas'; | |
} | |
if(day_diff === 1) return 'amanhã'; | |
if(day_diff === 2) return 'depois de amanhã'; | |
if(day_diff < 4) return datetime.toLocaleDateString('pt-BR', { weekday: 'long' }); | |
if(day_diff < 7 + (7 - datetime.getDay())) return 'em uma semana'; | |
if(Math.ceil(day_diff / 7) < 4) return 'em ' + Math.ceil(day_diff / 7) + ' semanas'; | |
if(datetime.getMonth() === new Date().getMonth() + 1) return 'no próximo mês'; | |
} | |
return datetime.toLocaleDateString() + ' às ' + datetime.toLocaleTimeString('pt-BR', {hour: "numeric", minute: "numeric"}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment