Last active
April 19, 2021 20:04
-
-
Save renatorib/3c6205472f7de0caa032e70fd1e186ed to your computer and use it in GitHub Desktop.
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
export const formatDate = (dateOrString, opts) => { | |
const date = new Date(dateOrString); | |
return new Intl.DateTimeFormat('pt-BR', opts).format(date); | |
} |
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
const tokens = { | |
DD: (date) => date.getDate().toString().padStart(2, '0'), | |
MM: (date) => (date.getMonth() + 1).toString().padStart(2, '0'), | |
YYYY: (date) => date.getFullYear().toString().padStart(4, '0'), | |
}; | |
export const formatDate = (dateOrString, format = 'DD/MM/YYYY') => { | |
const date = new Date(dateOrString); | |
return Object.entries(tokens).reduce( | |
(result, [pattern, fn]) => result.replace(new RegExp(pattern, 'g'), fn(date)), | |
format | |
); | |
}; |
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
const monthNames = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']; | |
const weekDayNames = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado']; | |
// Add literally any custom token... have fun | |
const tokens = { | |
DD: (date) => date.getDate().toString().padStart(2, '0'), | |
MM: (date) => (date.getMonth() + 1).toString().padStart(2, '0'), | |
YYYY: (date) => date.getFullYear().toString().padStart(4, '0'), | |
HH: (date) => date.getHours().toString().padStart(2, '0'), | |
mm: (date) => date.getMinutes().toString().padStart(2, '0'), | |
Mmmm: (date) => monthNames[date.getMonth()], | |
Mmm: (date) => monthNames[date.getMonth()].slice(0, 3), | |
Wwww: (date) => weekDayNames[date.getDay()], | |
Www: (date) => weekDayNames[date.getDay()].slice(0, 3), | |
}; | |
export const formatDate = (dateOrString, format = 'DD/MM/YYYY') => { | |
const date = new Date(dateOrString); | |
return Object.entries(tokens).reduce( | |
(result, [pattern, fn]) => result.replace(new RegExp(pattern, 'g'), fn(date)), | |
format | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment