我有一个 TimeSpan 代表客户端连接到我的服务器的时间量。我想向用户显示 TimeSpan。但我不想过于冗长地显示该信息(例如:2 小时 3 分钟 32.2345 秒 = 太详细了!)
例如:如果连接时间是...
> 0 seconds and < 1 minute -----> 0 Seconds
> 1 minute and < 1 hour -----> 0 Minutes, 0 Seconds
> 1 hour and < 1 day -----> 0 Hours, 0 Minutes
> 1 day -----> 0 Days, 0 Hours
当然,如果数字是 1(例如:1 秒、1 分钟、1 小时、1 天),我想将文本设为单数(例如:1 秒、1 分钟、1 小时、 1 天)。
如果没有大量的 if/else 子句,是否可以轻松实现这一点?这是我目前正在做的事情。
public string GetReadableTimeSpan(TimeSpan value)
{
string duration;
if (value.TotalMinutes < 1)
duration = value.Seconds + " Seconds";
else if (value.TotalHours < 1)
duration = value.Minutes + " Minutes, " + value.Seconds + " Seconds";
else if (value.TotalDays < 1)
duration = value.Hours + " Hours, " + value.Minutes + " Minutes";
else
duration = value.Days + " Days, " + value.Hours + " Hours";
if (duration.StartsWith("1 Seconds") || duration.EndsWith(" 1 Seconds"))
duration = duration.Replace("1 Seconds", "1 Second");
if (duration.StartsWith("1 Minutes") || duration.EndsWith(" 1 Minutes"))
duration = duration.Replace("1 Minutes", "1 Minute");
if (duration.StartsWith("1 Hours") || duration.EndsWith(" 1 Hours"))
duration = duration.Replace("1 Hours", "1 Hour");
if (duration.StartsWith("1 Days"))
duration = duration.Replace("1 Days", "1 Day");
return duration;
}
最佳答案
要摆脱复杂的 if 和 switch 结构,您可以使用基于 TotalSeconds 的字典查找来查找正确的格式字符串,并使用 CustomFormatter 来相应地格式化所提供的时间跨度。
public string GetReadableTimespan(TimeSpan ts)
{
// formats and its cutoffs based on totalseconds
var cutoff = new SortedList<long, string> {
{59, "{3:S}" },
{60, "{2:M}" },
{60*60-1, "{2:M}, {3:S}"},
{60*60, "{1:H}"},
{24*60*60-1, "{1:H}, {2:M}"},
{24*60*60, "{0:D}"},
{Int64.MaxValue , "{0:D}, {1:H}"}
};
// find nearest best match
var find = cutoff.Keys.ToList()
.BinarySearch((long)ts.TotalSeconds);
// negative values indicate a nearest match
var near = find<0?Math.Abs(find)-1:find;
// use custom formatter to get the string
return String.Format(
new HMSFormatter(),
cutoff[cutoff.Keys[near]],
ts.Days,
ts.Hours,
ts.Minutes,
ts.Seconds);
}
// formatter for forms of
// seconds/hours/day
public class HMSFormatter:ICustomFormatter, IFormatProvider
{
// list of Formats, with a P customformat for pluralization
static Dictionary<string, string> timeformats = new Dictionary<string, string> {
{"S", "{0:P:Seconds:Second}"},
{"M", "{0:P:Minutes:Minute}"},
{"H","{0:P:Hours:Hour}"},
{"D", "{0:P:Days:Day}"}
};
public string Format(string format, object arg, IFormatProvider formatProvider)
{
return String.Format(new PluralFormatter(),timeformats[format], arg);
}
public object GetFormat(Type formatType)
{
return formatType == typeof(ICustomFormatter)?this:null;
}
}
// formats a numeric value based on a format P:Plural:Singular
public class PluralFormatter:ICustomFormatter, IFormatProvider
{
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg !=null)
{
var parts = format.Split(':'); // ["P", "Plural", "Singular"]
if (parts[0] == "P") // correct format?
{
// which index postion to use
int partIndex = (arg.ToString() == "1")?2:1;
// pick string (safe guard for array bounds) and format
return String.Format("{0} {1}", arg, (parts.Length>partIndex?parts[partIndex]:""));
}
}
return String.Format(format, arg);
}
public object GetFormat(Type formatType)
{
return formatType == typeof(ICustomFormatter)?this:null;
}
}
关于c# - 如何生成 "human readable"字符串来表示 TimeSpan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16689468/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru