繁体   English   中英

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

[英]Javascript function to convert decimal years value into years, months and days

我需要一个函数来转换年、月和日的十进制值。 例如: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 个月)。

有什么帮助吗?

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

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);
}

我的贡献将十进制年转换为时间单位,范围从 eon(十亿年)到纳秒(十亿分之一秒),并以略带啰嗦的风格用逗号格式化输出。

转换时间的方法有很多种,必须要理解这些假设。 这是我的:

这基于 1) 每月平均有 30.436875 天,根据公历进行转换; 2) 4 年平均 730.485 小时的月份,包括 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

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

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

0 年9 个月0 天

你到底想要它做什么?

如果您希望它删除“0”值,那么您需要测试它们并且如果它们等于 0,则不要将它们附加到字符串中,例如:

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

我使用 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 年 -> 休息 0.25273972602739736
-3 个月 -> 休息 0.00273972602739736
-1 天 -> 休息 0.000001875240265258784
-0 小时 -> 休息 0.000001875240265258784
-0 分钟 -> 休息 0.000001875240265258784
2年3个月1天0小时0分钟

要获得秒数,可以很容易地将'seconds'添加到units数组,并将365.25*24*60*60converters数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM