【问题标题】:ReactNative / Momentjs date parsing issueReact Native / Moment Js日期解析问题
【发布时间】:2016-08-11 00:12:14
【问题描述】:

在 React Native 中使用 momentjs。下面的MomentT 函数正在根据请求的格式解析日期/时间,并且它显示的格式正确,但它给了我一个奇怪的时间,而不是日落的时间。它实际上似乎忽略了json.sys.sunset(在洛杉矶目前大约是 1470969909 在 unix 时间)并将其解析为下午 4:36:09,但它应该将其解析为下午 7:45:09。我究竟做错了什么?

以下是相关代码:

var moment = require('moment');

var MomentT = function(tod) {
  return moment(tod).format('h:mm:ss a');
};  

module.exports = function(latitude, longitude) {
  var url = `${rootUrl}&lat=${latitude}&lon=${longitude}`;
  console.log(url);
  return fetch(url)
    .then(function(response){
      return response.json();
    })
    .then(function(json){
      return {
        sunset: MomentT(json.sys.sunset)
      }
    })
    .catch(function(error) {
    console.log('There has been a problem with your fetch operation: ' + error.message);
    throw error;
});
}

【问题讨论】:

    标签: javascript react-native momentjs


    【解决方案1】:

    你需要解析new Date中的tod如下

    var MomentT = function(tod) {
      return moment(new Date(tod)).format('MMMM Do YYYY, h:mm:ss a');
    }; 
    

    根据docs,第一个参数必须是日期字符串

    【讨论】:

      【解决方案2】:

      moment(Number) 要求时间戳是自纪元以来的毫秒 数。你在几秒钟内过去了,所以你最终得到的日期是 1970 年的某个地方。

      两种解决方案:

      moment(tod * 1000)
      moment.unix(tod)
      

      记录在案的 herehere

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-24
        • 2012-08-16
        • 1970-01-01
        相关资源
        最近更新 更多