嗨,我一直在寻找一段时间,我似乎无法找到答案。
我必须在javascript中编写一个函数,该函数在参数中占用几天,然后将其转换为更易理解的字符串。
前:
function getFormatedStringFromDays(days)
{
var formatedString = "";
//... logic
return formatedString;
}
所以getFormatedStringFromDays(183)
返回的内容类似于6 months 3 days
。
答案 0 :(得分:1)
假设该年包含365天和每月 - 30天,答案可能如下所示。否则应该有更多的输入参数
function getFormatedStringFromDays(numberOfDays) {
var years = Math.floor(numberOfDays / 365);
var months = Math.floor(numberOfDays % 365 / 30);
var days = Math.floor(numberOfDays % 365 % 30);
var yearsDisplay = years > 0 ? years + (years == 1 ? " year, " : " years, ") : "";
var monthsDisplay = months > 0 ? months + (months == 1 ? " month, " : " months, ") : "";
var daysDisplay = days > 0 ? days + (days == 1 ? " day" : " days") : "";
return yearsDisplay + monthsDisplay + daysDisplay;
}
不是最优雅的解决方案,但应该有效
答案 1 :(得分:1)
Pure js:
function getFormatedStringFromDays(days) {
days = +days;
if(Number.isInteger(+days)){
var months = Math.floor(days / 30);
var mon_text = months <= 1 ? ' month ' : ' months ';
var days = days % 30;
var day_text = days <= 1 ? ' day' : ' days';
return months + mon_text + days + day_text;
} else {
return 'not a number';
}
}
console.log(getFormatedStringFromDays(1));
console.log(getFormatedStringFromDays(35));
console.log(getFormatedStringFromDays(183));
console.log(getFormatedStringFromDays('abc'));
console.log(getFormatedStringFromDays('123'));
&#13;