在React Native中格式化日期字符串 [英] Formatting a Date String in React Native
问题描述
我正在尝试在React Native中格式化日期字符串.
I'm trying to format a Date String in React Native.
例如:2016-01-04 10:34:23
Ex: 2016-01-04 10:34:23
以下是我正在使用的代码.
Following is the code I'm using.
var date = new Date("2016-01-04 10:34:23");
console.log(date);
我的问题是,当我在iPhone 6S上进行仿真时,它将打印星期一 Jan 04 2016 10:34:23 GMT + 0530(IST)
没问题.但是,如果我尝试使用iPhone 5S,它将无法打印任何内容.而且,如果您尝试使用类似 date.getMonth()
的方法来获取月份,它将打印"NaN"
.
My problem is, when I'm emulating this on a iPhone 6S, it'll print Mon Jan 04 2016 10:34:23 GMT+0530 (IST)
without any problem. But if I try with the iPhone 5S it prints nothing. And if you try to get the month by using a method like date.getMonth()
it'll print "NaN"
.
这是为什么?解决方法是什么?
Why is this? What is the workaround?
推荐答案
React Native的优点在于它支持许多JS库,例如Moment.js.使用moment.js将是处理日期/时间的更好/更简便的方法,而不是从头开始编码
The beauty of the React Native is that it supports lots of JS libraries like Moment.js. Using moment.js would be a better/easier way to handle date/time instead coding from scratch
只需在终端中运行它(如果使用React的内置包管理器, yarn add moment
也可以工作):
just run this in the terminal (yarn add moment
also works if using React's built-in package manager):
npm install moment --save
在您的React Native js页面中:
And in your React Native js page:
import Moment from 'moment';
render(){
Moment.locale('en');
var dt = '2016-05-02T00:00:00';
return(<View> {Moment(dt).format('d MMM')} </View>) //basically you can do all sorts of the formatting and others
}
您可以在此处查看一下moment.js官方文档 https://momentjs.com/docs/
You may check the moment.js official docs here https://momentjs.com/docs/
这篇关于在React Native中格式化日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!