I get full date in JavaScript. -> "Sun Feb 23 2020 10:12:46 GMT+0800 (CST)" I'd like to convert this into short date(date type, not string) -> "2020-02-23" How can I convert this?
There are a number of ways this can be achieved, however a simple approach that doesn't require a third-party library would be as follows:
const inputString = "Sun Feb 23 2020 10:12:46 GMT+0800 (CST)"; /* Parse date object directly from string of supplied format */ const date = new Date(inputString); /* Define helper function that pads a zero to front on string, if number less that 10 */ const padNumber = n => `${n < 10 ? '0' : ''}${n}` /* Format desired output string, and use padNumber help on date parts as needed */ const outputString = `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())}` console.log(outputString);
its not a build in function but you can always
iterate the string until the first number comes.
you start recording a 'date' string then,
then replace the whitespaces with dashes
and stop recording your date string at the first ':'
you could make a function out of this, or search for a built-in
You can use a moment package to fulfil your purpose. Here is the small example.
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import moment from 'moment';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
dateText: '',
};
}
onDOBDatePicked = (date) => {
this.setState({
dateText: moment(date).format('DD-MMM-YYYY')
});
}
componentDidMount () {
const date = "Sun Feb 23 2020 10:12:46 GMT+0800 (CST)";
this.onDOBDatePicked(date);
}
render() {
return (
<View>
<Text style={{ padding : 50 }}>
{this.state.dateText}
</Text>
</View>
);
}
}
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.