人类可读的持续时间格式【难度:4级】:
答案1:
public class HumanTimeFormat{
public static string formatDuration(int seconds){
string s = "";
int sec = seconds;
int[] divArr = {
60 * 60 * 24 * 365, 60 * 60 * 24, 60 * 60, 60, 1 };
string[] nameArr = {
"year","day","hour","minute","second"};
if (seconds == 0)
{
s = "now";
}
for (int i = 0; i< divArr.Length; i++)
{
int k = sec / divArr[i];
sec = sec % divArr[i];
if (k != 0)
{
string pref = "";
if (s != "")
{
if (sec == 0)
{
pref = " and ";
}
else
{
pref = ", ";
}
}
s = s + pref + k.ToString() + " " + nameArr[i];
s += k > 1 ? "s" : "";
}
}
return s;
}
}
答案2:
public class HumanTimeFormat{
public static string formatDuration(int seconds){
string s = "";
int sec = seconds;
int[] divArr = {
60 * 60 * 24 * 365, 60 * 60 * 24, 60 * 60, 60, 1 };
string[] nameArr = {
"year","day","hour","minute","second"};
if (seconds == 0)
{
s = "now";
}
for (int i = 0; i< divArr.Length; i++)
{
int k = sec / divArr[i];
sec = sec % divArr[i];
if (k != 0)
{
string pref = "";
if (s != "")
{
if (sec == 0)
{
pref = " and ";
}
else
{
pref = ", ";
}
}
s = s + pref + k.ToString() + " " + nameArr[i];
s += k > 1 ? "s" : "";
}
}
return s;
}
}
答案3:
using System;
using System.Collections.Generic;
using System.Linq;
public class HumanTimeFormat{
public static string formatDuration(int seconds){
if (seconds == 0){
return "now";
}
var time = TimeSpan.FromSeconds(seconds);
var timesList = new string[]{
MultipleFormat("year", time.Days / 365),
MultipleFormat("day", time.Days % 365),
MultipleFormat("hour", time.Hours),
MultipleFormat("minute", time.Minutes),
MultipleFormat("second", time.Seconds)
};
var list = timesList.Where(x => x != string.Empty).ToList();
if (list.Count == 1){
return list.First();
}
var firstPart = string.Join(", ", list.Take(list.Count - 1));
return $"{firstPart} and {list.Last()}";
}
private static string MultipleFormat(string measure, double count){
var c =