如何在React-Native-IOS中格式化日期

时间:2016-11-23 10:00:36

标签: date react-native date-format

我用以下来显示日期:

var formattedDate = new Date(date).toString();
    console.log("DATE >> ", formattedDate);

结果:

  

'日期>>' ,'Wed Nov 23 2015 05:30:00'

我的date格式如下:

date= 2015-11-23

但我想在date

中以 "DD MMM YYYY" 格式格式化我的react-native-ios.

6 个答案:

答案 0 :(得分:4)

使用date.getDay(),date.getMonth()和date.getYear()从日期中提取日期年份,然后根据需要使用它:)

var formattedDate = new Date(date);
var newDate = formattedDate.getDay().toString() + " " + formattedDate.getMonth().toString() + " " + formattedDate.getYear().toString();

作为替代,您也可以使用moment.js。有很多有用的功能。

var newDate = moment(Date(yourDate)).format('DD-MM-YYYY');

导入Moment JS:

import moment from 'moment';

安装Moment JS:

npm install moment

答案 1 :(得分:1)

var dateee = new Date(this.dateUpdate);//this.dateUpdate = 1488506939000
var wholeDate = dateee.getFullYear() + '-' + ('0' + (dateee.getMonth() + 1)).slice(-2) + '-' + ('0' + dateee.getDate()).slice(-2) + ' ' + ('0' + dateee.getHours()).slice(-2) + ':' + ('0' + dateee.getMinutes()).slice(-2);
console.log('----- ' + this.dateUpdate + '     ' + wholeDate);


//----- 1488506939000  2017-03-03 10:08

答案 2 :(得分:0)

@Ataomega。要获取Date实例的日期,您需要使用formattedDate.getDate()。toString()而不是formattedDate.getDay()。toString()。否则,您将获得一周中的某一天。查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getDay了解详情。

答案 3 :(得分:0)

使用date-fnsformat()函数

npm install date-fns --save

import { format } from 'date-fns'

format(new Date(), 'MMMM Do, YYYY H:mma')

Documentation for format()

瞬间很棒,但是对于常见用法来说非常大,不幸的是它不是模块化的,因此必须导入整个程序包才能使用它。

答案 4 :(得分:0)

嘿,您可以使用自由时刻:https://momentjs.com/ 您可以使用以下格式设置任何日期:

moment().format('yourDateHere, DD:MM:YYYY');

答案 5 :(得分:-1)

代码:

handleDatePicked = (date) => {
    console.log(date);
    var ds = date.toString();

    var date = moment(new Date(ds.substr(0, 16)));
    console.log("54874=========>"+date.format("DD/MM/YYYY"));

    this.setState({ 'date_of_birth': date.format("DD/MM/YYYY") });

};

输出:

Sun Mar 17 2019 15:38:00 GMT+0530 (India Standard Time)
17/03/2019