Skip to content

Instantly share code, notes, and snippets.

@renatorib
Last active April 19, 2021 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renatorib/3c6205472f7de0caa032e70fd1e186ed to your computer and use it in GitHub Desktop.
Save renatorib/3c6205472f7de0caa032e70fd1e186ed to your computer and use it in GitHub Desktop.
export const formatDate = (dateOrString, opts) => {
const date = new Date(dateOrString);
return new Intl.DateTimeFormat('pt-BR', opts).format(date);
}
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
);
};
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