美文网首页
React Native时间戳转换为YYYY-MM-DD格式

React Native时间戳转换为YYYY-MM-DD格式

作者: HJXu | 来源:发表于2017-07-20 17:33 被阅读1263次

情景再现:
RN项目中后台返回的时间是一个时间戳,而页面需要展示为常见的YYYY-MM-DD格式,这个时候我们该如何进行转换呢?

//导入 moment
import moment from 'moment';

自定义组件

export default class myApp extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={{flex: 1}}>
          <View style={{flex: 1, backgroundColor: 'red'}}></View>
          <View style={{flex: 2, backgroundColor: 'orange'}}>
                <Text>{`今天是${this.todayDate()}离国庆还有十天`}</Text></View>
          <View style={{flex: 3, backgroundColor: 'steelblue'}} />
        </View>
      </View>
    );
  }

  todayDate(){
    var today = new Date();
    return this.date(today,'YY,MM,DD')
  }
}

封装方法

  date (date,fomatter){
    if (!date)return '';
    var fmt = fomatter || 'YYYY年MM月DD';
    return moment(date).format(fmt);
  }

样式文件

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
AppRegistry.registerComponent('myApp', () => myApp);

相关文章

网友评论

      本文标题:React Native时间戳转换为YYYY-MM-DD格式

      本文链接:https://www.haomeiwen.com/subject/narjkxtx.html