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
JavaScript
x
23
23
1
export function pegaDia(str) {
2
var monthNames = [
3
"Jan",
4
"Fev",
5
"Mar",
6
"Abr",
7
"Mai",
8
"Jun",
9
"Jul",
10
"Ago",
11
"Set",
12
"Out",
13
"Nov",
14
"Dez",
15
];
16
17
var d = new Date(str); //converts the string into date object
18
var m = d.getMonth(); //get the value of month
19
var n = monthNames[m];
20
var dia = d.getDate() + 1;
21
return { dia, n };
22
}
23
JavaScript
1
44
44
1
import Head from "next/head";
2
import styles from "./styles.module.scss";
3
import api from "../../services/api";
4
import { useEffect, useState } from "react";
5
import { pegaDia } from "./functions";
6
7
export default function Board() {
8
const [passagens, setPassagens] = useState([] as any);
9
10
useEffect(() => {
11
async function loadPassagens() {
12
const response = await api.get("ZLIMIT_1?limit=10");
13
//console.log(response.data.slice(0, 10));
14
setPassagens(response.data.slice(0, 10));
15
}
16
loadPassagens();
17
});
18
19
return (
20
<>
21
<Head>
22
<title>Passagens Promocionais</title>
23
</Head>
24
25
<div className={styles.container}>
26
27
<div className={styles.listapassagens}>
28
{passagens.map((passagens) => {
29
return (
30
<article key={passagens.created}>
31
<strong>{passagens.arrival_ap_city}</strong>
32
<br /> <span>Saindo de: {passagens.departure_ap_city}</span>
33
**<span>Ida ${pegaDia("{ passagens.departure_date }")}</span>**
34
<span>Volta {passagens.returning_date}</span>
35
<span>Preço {passagens.price_w_fees}</span>
36
</article>
37
);
38
})}
39
</div>
40
</div>
41
</>
42
);
43
}
44
Advertisement
Answer
Seems you want something like this…
First, create a date formatter for your locale (or a specific one if you want)
JavaScript
1
6
1
const locale = undefined; // leave undefined to use the current locale
2
const formatter = new Intl.DateTimeFormat(locale, {
3
day: "numeric",
4
month: "short",
5
});
6
Then use it to format your dates
JavaScript
1
2
1
<span>Ida {formatter.format(new Date(passagens.departure_date))}</span>
2
You could automatically parse the date strings when setting your data to avoid calling new Date()
every render
JavaScript
1
5
1
setPassagens(response.data.slice(0, 10).map(({ departure_date, rest }) => ({
2
rest,
3
departure_date: new Date(departure_date),
4
}));
5