[英]how to convert full date into short type date in javascript?
I get full date in JavaScript.我在 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? ->“Sun Feb 23 2020 10:12:46 GMT+0800 (CST)”我想将其转换为短日期(日期类型,而不是字符串)->“2020-02-23”我该如何转换?
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.您可以使用 moment 包来实现您的目的。 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>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.