Reputation: 123
I'm trying to convert a date returned to me as a string (format: "2020-06-15T12:41:16+00:00") into a date object.
So I get my list of items in a fetchResults() function, and I thought I could do the conversion at the time of the .map in the return, only I don't really see the syntax I could use...
Anyone have an idea?
My component react :
const ResultList = ({userId}) => {
const [resultsList, setResultList] = useState({})
const [loading, setLoading] = useState(true)
useEffect(() => {
fetchResults()
}, [userId])
const fetchResults = async () => {
try {
const data = await resultsAPI.findResultsByUser(userId)
setResultList(data)
setLoading(false)
} catch (error) {
console.log(error)
}
}
return(
<>
{!loading &&
<>
<h3 className="resultCount">You have {resultsList.length} results</h3>
<ul className="resultsList">
{resultsList.map(result => {
return(
<li key={result.id} className="resultItem">
<span>{result.resultDate}</span> //HERE CONVERT STRING TO DATE
<span>{result.Maturity}</span>
</li>
)
})}
</ul>
</>
}
</>
)
}
export default ResultList
Thanks !
Upvotes: 0
Views: 1201
Reputation: 1
<li key={result.id} className="resultItem">
<span> {new Date(`${result.resultDate}`).toDateString()}</span> // use template literals
<span>{result.Maturity}</span>
Use this will defenitly work.
Upvotes: 0
Reputation: 1590
Use moment.js. You can able to convert a date string to any desired date format. For that you need to know the current date format of a date string
import moment from "moment";
let resultDate = '2020-06-15 17:44:18'; // which is YYYY-MM-DD hh:mm:ss
<span>{moment(resultDate, 'YYYY-MM-DD hh:mm:ss').format('MM-DD-YYYY')}</span> // It will return 06-15-2020
Upvotes: 1