I want to convert this { passagens.departure_date } into date like 1 nov, 2 dez examples. This { passagens.departure_date } is like this value: 2022-10-02T00:00:00Z. I just want to pick the right date in strings.
I Try everything. This is my code Also i did the function pegaDia
export function pegaDia(str) { var monthNames = [ "Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez", ]; var d = new Date(str); //converts the string into date object var m = d.getMonth(); //get the value of month var n = monthNames[m]; var dia = d.getDate() + 1; return { dia, n }; }
import Head from "next/head"; import styles from "./styles.module.scss"; import api from "../../services/api"; import { useEffect, useState } from "react"; import { pegaDia } from "./functions"; export default function Board() { const [passagens, setPassagens] = useState([] as any); useEffect(() => { async function loadPassagens() { const response = await api.get("ZLIMIT_1?limit=10"); //console.log(response.data.slice(0, 10)); setPassagens(response.data.slice(0, 10)); } loadPassagens(); }); return ( <> <Head> <title>Passagens Promocionais</title> </Head> <div className={styles.container}> <div className={styles.listapassagens}> {passagens.map((passagens) => { return ( <article key={passagens.created}> <strong>{passagens.arrival_ap_city}</strong> <br /> <span>Saindo de: {passagens.departure_ap_city}</span> **<span>Ida ${pegaDia("{ passagens.departure_date }")}</span>** <span>Volta {passagens.returning_date}</span> <span>Preço {passagens.price_w_fees}</span> </article> ); })} </div> </div> </> ); }
Advertisement
Answer
Seems you want something like this…
First, create a date formatter for your locale (or a specific one if you want)
const locale = undefined; // leave undefined to use the current locale const formatter = new Intl.DateTimeFormat(locale, { day: "numeric", month: "short", });
Then use it to format your dates
<span>Ida {formatter.format(new Date(passagens.departure_date))}</span>
You could automatically parse the date strings when setting your data to avoid calling new Date()
every render
setPassagens(response.data.slice(0, 10).map(({ departure_date, ...rest }) => ({ ...rest, departure_date: new Date(departure_date), }));