Javascript函数将十进制年份值转换为年,月和日

时间:2014-02-27 03:48:51

标签: javascript

我需要一个函数来转换年,月和日的年数十进制值。例如:1。5年= 1年,6个月。 2.2527397260273973年= 2年,3个月和1天。

我开始使用这个功能:

function yearsToYearsMonthsDays(value){
var years = Math.floor(value);
var months =  Math.floor( (value - years) /(1/12) );
var days = Math.floor ( ( (value - years) /(1/12) - Math.floor((value - years) /(1/12)) ) / (1/365) );
var result = years + " years, " + months + " months, " + days + " days";
    Logger.log(result);
}

但有时它不起作用(例如:0.75不会产生9个月)。

任何帮助?

4 个答案:

答案 0 :(得分:4)

我认为最好的方法是将所有内容更改为日期,例如:

function yearsToYearsMonthsDays(value)
{
    var totalDays = value * 365;
    var years = math.floor(totalDays/365);
    var months = math.floor((totalDays-(years *365))/30);
    var days = math.floor(totalDays - (years*365) - (months * 30));
    var result = years + " years, " + months + " months, " + days + " days";
    Logger.log(result);
}

答案 1 :(得分:0)

你的脚本在这里运行良好(在firebug控制台中测试)。

以0.75作为参数调用函数会产生:

  
    

0年, 9个月,0天

  

你到底希望它做什么?

如果你想删除" 0"值,那么你需要测试它们,如果它们等于0,就不要将它们附加到字符串中,例如:

var result = "";
if(years !=0){result += year + " years"}

答案 2 :(得分:0)

我的贡献将十进制年份转换为时间单位,范围从eons(十亿年)到纳秒(十亿分之一秒),输出格式为逗号,略显繁琐。

有许多方式来转换时间,必须理解这些假设。这是我的:

根据公历,1)平均月份为30.436875天; 2)一个月平均为730.485小时,为期4年,其中包括1个闰年; 3)每年有8765.82小时(不是8760)。当然,这些内部常量并不适合每个应用程序,但应该足够通用。例如,我的函数在OP的例子中添加了大约一分钟的时间:

  

2.2527397260273973年= 2年,3个月和1天

其中

getTimeFromYears( 2.2527397260273973 );

输出“2年,3个月,1天57秒”。

有些单位似乎没必要,例如,当你有几天和几个月,而几十年当你有几年和几个世纪,但那些可以很容易地添加到逻辑中。运行代码段以查看示例。

function getTimeFromYears( _years ) {
// to omit a unit from the output, multiply its value by zero; see gyears

    "use strict";

    var _hoursInEon            = 8765820000000     // eon =         1,000,000,000 years (billion)
        , _hoursInGalacticYear = 2016138600000     // galactic year = 230,000,000 years (230 million)
        , _hoursInEpoch        =    8765820000     // epoch =           1,000,000 years (million)
        , _hoursInMillenium    =       8765820     // millenium =           1,000 years
        , _hoursInCentury      =        876582   
        , _hoursInYear         =          8765.82  // often cited as 8760, or 730 * 12  // 365.2425 days in year
        , _hoursInMonth        =           730.485 // hours average per month for a 4-year period which includes 1 leap year
                                                   // average month has 30.436875 days, Gregorian calendar
        , _hoursInDay          =            24
        , _hoursInHour         =             1
        , _hoursInMinute       =             0.0166666666666667
        , _hoursInSecond       =             0.000277778
        , _hoursInMillisecond  =             0.000000277778       // A millisecond is one-thousandth of a second
        , _hoursInNanosecond   =             0.000000000000277778 // A nanosecond is one-billionth of a second


        , totalHours = _years * _hoursInYear
        
        , eons   = Math.floor(   totalHours
                    / _hoursInEon )

        , gyears = Math.floor( ( totalHours - ( eons * _hoursInEon ) )
                    / _hoursInGalacticYear ) * 0

        , epochs = Math.floor( ( totalHours - ( eons * _hoursInEon ) - ( gyears * _hoursInGalacticYear ) )
                    / _hoursInEpoch )

        , mills  = Math.floor( ( totalHours - ( eons * _hoursInEon ) - ( gyears * _hoursInGalacticYear ) - ( epochs * _hoursInEpoch ) )
                    / _hoursInMillenium )

        , cents  = Math.floor( ( totalHours - ( eons * _hoursInEon ) - ( gyears * _hoursInGalacticYear ) - ( epochs * _hoursInEpoch ) - ( mills * _hoursInMillenium ) )
                    / _hoursInCentury )

        , years  = Math.floor( ( totalHours - ( eons * _hoursInEon ) - ( gyears * _hoursInGalacticYear ) - ( epochs * _hoursInEpoch ) - ( mills * _hoursInMillenium ) - ( cents * _hoursInCentury ) )
                    / _hoursInYear )
    
        , months = Math.floor( ( totalHours - ( eons * _hoursInEon ) - ( gyears * _hoursInGalacticYear ) - ( epochs * _hoursInEpoch ) - ( mills * _hoursInMillenium ) - ( cents * _hoursInCentury ) - ( years * _hoursInYear ) )
                    / _hoursInMonth )
    
        , days   = Math.floor( ( totalHours - ( eons * _hoursInEon ) - ( gyears * _hoursInGalacticYear ) - ( epochs * _hoursInEpoch ) - ( mills * _hoursInMillenium ) - ( cents * _hoursInCentury ) - ( years * _hoursInYear ) - ( months * _hoursInMonth ) )
                    / _hoursInDay )
    
        , hours  = Math.floor( ( totalHours - ( eons * _hoursInEon ) - ( gyears * _hoursInGalacticYear ) - ( epochs * _hoursInEpoch ) - ( mills * _hoursInMillenium ) - ( cents * _hoursInCentury ) - ( years * _hoursInYear ) - ( months * _hoursInMonth ) - ( days * _hoursInDay ) )
                    / _hoursInHour )
    
        , mins  = Math.floor( ( totalHours - ( eons * _hoursInEon ) - ( gyears * _hoursInGalacticYear ) - ( epochs * _hoursInEpoch ) - ( mills * _hoursInMillenium ) - ( cents * _hoursInCentury ) - ( years * _hoursInYear ) - ( months * _hoursInMonth ) - ( days * _hoursInDay ) - ( hours * _hoursInHour ) )
                    / _hoursInMinute ) 

        , secs  = Math.floor( ( totalHours - ( eons * _hoursInEon ) - ( gyears * _hoursInGalacticYear ) - ( epochs * _hoursInEpoch ) - ( mills * _hoursInMillenium ) - ( cents * _hoursInCentury ) - ( years * _hoursInYear ) - ( months * _hoursInMonth ) - ( days * _hoursInDay ) - ( hours * _hoursInHour ) - ( mins * _hoursInMinute ) )
                    / _hoursInSecond )

        , msecs = Math.floor( ( totalHours - ( eons * _hoursInEon ) - ( gyears * _hoursInGalacticYear ) - ( epochs * _hoursInEpoch ) - ( mills * _hoursInMillenium ) - ( cents * _hoursInCentury ) - ( years * _hoursInYear ) - ( months * _hoursInMonth ) - ( days * _hoursInDay ) - ( hours * _hoursInHour ) - ( mins * _hoursInMinute ) - ( secs * _hoursInSecond ) )
                    / _hoursInMillisecond )

        , nsecs = Math.floor( ( totalHours - ( eons * _hoursInEon ) - ( gyears * _hoursInGalacticYear ) - ( epochs * _hoursInEpoch ) - ( mills * _hoursInMillenium ) - ( cents * _hoursInCentury ) - ( years * _hoursInYear ) - ( months * _hoursInMonth ) - ( days * _hoursInDay ) - ( hours * _hoursInHour ) - ( mins * _hoursInMinute ) - ( secs * _hoursInSecond ) - ( msecs * _hoursInMillisecond ) )
                    / _hoursInNanosecond )


        , _eonsPhrase   = ( eons   < 1 ? '' : eons   === 1 ? '1 eon'           : addCommas( eons   ) + ' eons'           )
        , _gyearsPhrase = ( gyears < 1 ? '' : gyears === 1 ? '1 galactic year' : addCommas( gyears ) + ' galactic years' )
        , _epochsPhrase = ( epochs < 1 ? '' : epochs === 1 ? '1 epoch'         : addCommas( epochs ) + ' epochs'         )
        , _millsPhrase  = ( mills  < 1 ? '' : mills  === 1 ? '1 millenium'     : mills  + ' millenia'  )
        , _centsPhrase  = ( cents  < 1 ? '' : cents  === 1 ? '1 century'       : cents  + ' centuries' )
        , _yearsPhrase  = ( years  < 1 ? '' : years  === 1 ? '1 year'          : years  + ' years'     )
        , _monthsPhrase = ( months < 1 ? '' : months === 1 ? '1 month'         : months + ' months'    )
        , _daysPhrase   = ( days   < 1 ? '' : days   === 1 ? '1 day'           : days   + ' days'      )
        , _hoursPhrase  = ( hours  < 1 ? '' : hours  === 1 ? '1 hour'          : hours  + ' hours'     )
        , _minsPhrase   = ( mins   < 1 ? '' : mins   === 1 ? '1 minute'        : mins   + ' minutes'   )
        , _secsPhrase   = ( secs   < 1 ? '' : secs   === 1 ? '1 second'        : secs   + ' seconds'   )
        , _msecsPhrase  = ( msecs  < 1 ? '' : msecs  === 1 ? '1 millisecond'   : addCommas( msecs ) + ' milliseconds' )
        , _nsecsPhrase  = ( nsecs  < 1 ? '' : nsecs  === 1 ? '1 nanosecond'    : addCommas( nsecs ) + ' nanoseconds'  )

        , _phrasePart = new Array(13)
        , _phrasesInUse = 0
        , _phrasesUsed  = 0
        , _joiner = ','
        , _result = ''
    ;


    ////////////////////////////////////////////////////
    // cosmetic adjustments
    if( eons > 999999 ) { _joiner = ';'; }
    if( secs > 0 || mins > 0 ) { _msecsPhrase = _nsecsPhrase = ''; } 
    ////////////////////////////////////////////////////

    _phrasePart[  0 ] = _eonsPhrase;
    _phrasePart[  1 ] = _gyearsPhrase;
    _phrasePart[  2 ] = _epochsPhrase;
    _phrasePart[  3 ] = _millsPhrase;
    _phrasePart[  4 ] = _centsPhrase;
    _phrasePart[  5 ] = _yearsPhrase;
    _phrasePart[  6 ] = _monthsPhrase;
    _phrasePart[  7 ] = _daysPhrase;
    _phrasePart[  8 ] = _hoursPhrase;
    _phrasePart[  9 ] = _minsPhrase;
    _phrasePart[ 10 ] = _secsPhrase;
    _phrasePart[ 11 ] = _msecsPhrase;
    _phrasePart[ 12 ] = _nsecsPhrase;

    // count the phrase pieces to use
    for( var i = 0; i < _phrasePart.length; i++ ) {
        if( _phrasePart[ i ].length ) { _phrasesInUse++; }
    }

    // assemble the output
    for( var i = 0; i < _phrasePart.length; i++ ) {
        if( _phrasePart[ i ].length ) {
            _result += _phrasePart[ i ];
            _phrasesUsed++;

            // only for the last phrase
            if( _phrasesInUse - _phrasesUsed === 1 ) {
                _result += ' and ';
            
            } else
            if( _phrasesInUse - _phrasesUsed > 0 ) {
                _result += ( _joiner + ' ' );
            }
        }
    }

    return _result;
};


function addCommas(t) {
    t += ""; var x = t.split("."), x1 = x[0], x2 = x.length > 1 ? "." + x[1] : "";
    for (var r = /(\d+)(\d{3})/; r.test(x1); ) x1 = x1.replace(r, "$1,$2");
    return x1 + x2;
};


console.log( 'getTimeFromYears( .75 ) -> ' + getTimeFromYears( .75 ) ); // 9 months
console.log( 'getTimeFromYears( 9/12 ) -> ' + getTimeFromYears( 9/12 ) ); // 9 months
console.log( 'getTimeFromYears( 1/365.2425 ) -> ' + getTimeFromYears( 1/365.2425 ) ); // 1 day
console.log( 'getTimeFromYears( 1/365.2425 * 14 ) -> ' + getTimeFromYears( 1/365.2425 * 14 ) ); // 14 days
console.log( 'getTimeFromYears( 1/365.2425 / 24 ) -> ' + getTimeFromYears( 1/365.2425 / 24 ) ); // 1 hour
console.log( 'getTimeFromYears( 1/365.2425 / 24 * 730.485 ) -> ' + getTimeFromYears( 1/365.2425 / 24 * 730.485 ) ); // 1 month
console.log( 'getTimeFromYears( 1/365.2425 * 0.0000000000000115741 ) -> ' + getTimeFromYears( 1/365.2425 * 0.0000000000000115741 ) ); // 1 nanosecond
console.log( 'getTimeFromYears( 1/365.2425 / 24 * 0.000000000000277778 ) -> ' + getTimeFromYears( 1/365.2425 / 24 * 0.000000000000277778 ) ); // 1 nanosecond
console.log( 'getTimeFromYears( 1/365.2425 / 24 * 0.000000000000277778 * 12000 ) -> ' + getTimeFromYears( 1/365.2425 / 24 * 0.000000000000277778 * 12000 ) ); // 12,000 nanoseconds
console.log( 'getTimeFromYears( 1/365.2425 / 24 * 0.000000000000277778 * 1000000 ) -> ' + getTimeFromYears( 1/365.2425 / 24 * 0.000000000000277778 * 1000000 ) ); // 1 millisecond
console.log( 'getTimeFromYears( 1/365.2425 / 24 * 0.000000000000277778 * 12345678 ) -> ' + getTimeFromYears( 1/365.2425 / 24 * 0.000000000000277778 * 12345678 ) ); // 12 milliseconds and 345,678 nanoseconds
console.log( 'getTimeFromYears( 123456789 ) -> ' + getTimeFromYears( 123456789 ) ); // 123 epochs, 456 millenia, 7 centuries, 88 years, 11 months, 30 days, 10 hours, 29 minutes and 5 seconds
console.log( 'getTimeFromYears( 9876543210 ) -> ' + getTimeFromYears( 9876543210 ) ); // 9 eons, 876 epochs, 543 millenia, 2 centuries, 10 years and 11 seconds
console.log( 'getTimeFromYears( 2.2527397260273973 ) -> ' + getTimeFromYears( 2.2527397260273973 ) ); // 2 years, 3 months, 1 day and 57 seconds

答案 3 :(得分:0)

我说过使用jorgeregidor的答案,我稍微概括了一下。

function years_to_ymdh(value) {
    console.log('initialy : '+ value + ' years');

    var results=[], rest=value;
    var units=['years', 'months', 'days', 'hours', 'minutes'];
    var converters=[1, 12, 365.25, 365.25*24, 365.25*24*60];

    units.forEach(function(d,i){
        if (i==0) results[i] = Math.floor(rest);
        else results[i] = Math.floor(rest * converters[i]);
        if (results[i] != 0) rest = rest % (results[i]/converters[i]);
        console.log('-'+results[i]+' '+d+' -> rest', rest);
    });

    var text = results.map( (d,i) => d+' '+units[i] ).join(', ');
    console.log(text);

    // return text;
    return results;
}
  

years_to_ymdh(2.2527397260273973)
   - 2年 - &gt;休息0.25273972602739736
  -3个月 - &gt;休息0.00273972602739736
  -1天 - &gt;休息0.000001875240265258784
  -0小时 - &gt;休息0.000001875240265258784
  -0分钟 - &gt;休息0.000001875240265258784
  2年,3个月,1天,0小时,0分钟

要获得秒数,将'seconds'添加到units数组并将365.25*24*60*60添加到converters数组非常容易。