我想将这个{passagens.departure_date}转换为日期,例如1年11月,2年12月。{passagens.departure_date}的值是这样的:2022-10-02T00:00:00Z。我只是想在字符串中选择正确的日期。
我什么都试。这是我的代码,我也做了函数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>
</>
);
}
似乎你想要这样的东西…
首先,为您的区域设置创建一个日期格式化程序(如果需要,也可以指定一个)
const locale = undefined; // leave undefined to use the current locale
const formatter = new Intl.DateTimeFormat(locale, {
day: "numeric",
month: "short",
});
然后用它来格式化你的日期
<span>Ida {formatter.format(new Date(passagens.departure_date))}</span>
您可以在设置数据时自动解析日期字符串,以避免每次渲染时调用new Date()
setPassagens(response.data.slice(0, 10).map(({ departure_date, ...rest }) => ({
...rest,
departure_date: new Date(departure_date),
}));