I am trying to get only year from timestamp values using substring
. The timestamp value looks like 2020-11-19T17:26:53.561Z
. In my case, as you can see the below code, paid_date
is the timestamp value.
const invoices = [
{paid_date: "2020-11-19T17:26:53.561Z", amount: 50},
...
];
useEffect(() => {
const new = invoices.map(invoice => ({
paid_year: +invoice.paid_date.substr(0, 4),
paid_month: +invoice.paid_date.substr(5, 2),
amount: +invoice.amount
}))
console.log(new);
}, [invoices, isMountedRef]);
I expected the paid_year like 2020 as the result, but it returns the below array.
0: {paid_year: 2020, paid_month: 11, amount: 240}
1: {paid_year: false, paid_month: 11, amount: 500}
2: {paid_year: false, paid_month: 11, amount: 500}
3: {paid_year: true, paid_month: 12, amount: 20}
4: {paid_year: false, paid_month: 5, amount: 10}
5: {paid_year: false, paid_month: 3, amount: 5}
...
Why does it return the first paid_year
is 2020
but others are boolean
? I tried to use moment.js as well as substr
, substring
and slice
methods. The weird thing is that the result was correct what I expected only few times.
UPDATE: The new
variable name is just my idea, so that's beside the point. Same result whatever the name I used rather than new
.
And the invoices
is the axios api response and from my PostgreSQL database.
I am not sure if it is because of wrong usage of useEffect
.
It worked well outside useEffect
.
My brother you can deal with dates in multiple ways in react. If you have lot off stuff and things to do with dates then moment.js is best package out there.
here is the link: https://momentjs.com/docs/
do install: npm install moment
here is one use case
import moment from 'moment' const invoices = [ {paid_date: "2020-11-19T17:26:53.561Z", amount: 50}, ... ]; useEffect(() => { const new = invoices.map(invoice => ({ paid_year: +invoice.paid_date.moment.formate('YYYY'), paid_month: +invoice.paid_date.moment.formate('M'), amount: +invoice.amount })) console.log(new); }, [invoices, isMountedRef]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.