【问题标题】:Get Years months days hours minutes from moment from duration从持续时间中获取年月日小时分钟
【发布时间】:2021-06-05 14:11:48
【问题描述】:
const seconds = 1000000

var now = moment(moment.duration(seconds).asSeconds()).format('Y[y],M[m],D[d],H[h]')

我想将此秒格式化为年、月、日、小时、分钟,所以我无法找到我出错的地方如何在 React 本机中获得这种格式

【问题讨论】:

    标签: react-native momentjs


    【解决方案1】:

    此代码可能对您有所帮助

    export function formatDate(seconds) {
       var d = new Date(seconds*1000),
       month = '' + (d.getMonth() + 1),
       day = '' + d.getDate(),
       year = d.getFullYear();
    
      if (month.length < 2) 
          month = '0' + month;
      if (day.length < 2) 
          day = '0' + day;
    
      return [day,month,year].join('/');
    }
    

    此代码将返回 dd/mm/yyyy。如果你想返回日期+时间,那么你只需返回

    export function formatDate(seconds) {
       var d = new Date(seconds*1000)
        return d.toLocaleString()
    }
    

    如果您想获取剩余时间、日期、月份和年份,那么您应该使用此代码

    function secondsToHms(sec) {
        sec = Number(sec);
        var y = Math.floor(sec/31536000) //<<years
        var w= Math.floor(y*31536000)
        var w1=Math.floor(w-sec)
        w=Math.floor(Math.abs(w1)/604800)//<<weeks
        var d=Math.floor(Math.abs(w)*604800)
        var d1=Math.floor(Math.abs(d)-Math.abs(w1))
        d=Math.floor(Math.abs(d1)/86400)
        d=Math.abs(d)                //<<day
        var h = Math.floor(d*86400);
        h=Math.floor(h-Math.abs(d1))
        h=Math.floor(Math.abs(h)/3600)//<<hours
        var m = Math.floor(sec % 3600 / 60);//<<minutes
        var s = Math.floor(sec % 3600 % 60);//<<seconds
      
        var yDisplay = y > 0 ? y + (y == 1 ? " year, " : " years, ") : "0 year, ";
        var wDisplay = w > 0 ? w + (w == 1 ? " week, " : " weeks, ") : "0 week, ";
        var dDisplay = d > 0 ? d + (d == 1 ? " day, " : " days, ") : "0 day, ";
        var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "0 hour, ";
        var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "0 minute, ";
        var sDisplay = s > 0 ? s + (s == 1 ? " second. " : " seconds. ") : "0 second. ";
    
        return yDisplay + wDisplay + dDisplay + hDisplay + mDisplay + sDisplay;
      }
      console.log(secondsToHms(1000000))

    【讨论】:

    • 嗨@shammi 我不想这样,我想分开。比如 48 分钟,所以我希望它变成 0 年 0 个月 0 天 0 小时 48 分钟。
    • 哦,好的。等等我给你写个新代码请稍等
    • 我在片刻发现了这个 .format('Y[y],M[m],D[d]') 这在 React js 中有效,但在 React Native 上无效,如果你知道的话
    • 我认为当时出了点问题。我为你写了一个代码,请尝试一下并告诉我。
    猜你喜欢
    • 1970-01-01
    • 2021-06-06
    • 2020-05-20
    • 2012-05-25
    • 2011-07-26
    • 1970-01-01
    • 2015-01-18
    • 2015-07-16
    • 2011-04-14
    相关资源
    最近更新 更多