我想在TextBox只小时和分钟显示
var test = dataRow.Field<TimeSpan>("fstart").ToString();
//test ="08:00:00"
var tb = (TextBox) gridViewRow.Cells[2].FindControl("fstart");
tb.Text = test;
如何只显示小时和分钟"hh.mm"
您需要将数据转换为时间跨度,然后使用格式:"hh\:mm"
string test ="08:00:00";
TimeSpan ts = TimeSpan.Parse(test);
Console.Write(ts.ToString(@"hh\:mm"));
你的情况:
var test = dataRow.Field<TimeSpan>("fstart").ToString(@"hh\:mm"));
请记住逃脱结肠:
有没有必要从hh.mm.ss
转换为hh.mm
。 TimeSpan
被存储为数字蜱(蜱1 == 100纳秒),并没有固有的格式。你所要做的,是将TimeSpan
转换为人类可读的字符串!这就是所谓的格式。如果你没有明确指定格式,默认格式将被使用。在这种情况下hh.mm.ss
。
string formatted = timespan.ToString(@"hh\.mm");
注意:因为.NET 4.0 ToString
的此重载存在。它不支持的日期和时间占位符分隔符号!因此,你必须把它们作为(逃脱)字符串文字。
格式化字符串通常使用的方法似乎并不为一些奇怪的原因(与.NET 3.5测试)工作。 (它不会使任何差异是否逃脱分隔符与否):
var timespan = TimeSpan.FromSeconds(1234);
string formatted = String.Format("{0:hh.mm}", timespan); // ==> 00:20:34
但是,您可以构建这样的字符串
string formatted =
String.Format("{0:00}.{1:00}", Math.Floor(timespan.TotalHours), timespan.Minutes);
或与VS2015开始/ C#6.0,使用字符串插值:
string formatted = $"{Math.Floor(timespan.TotalHours):00}.{timespan.Minutes:00}";
您可以使用时间跨度的方法:
ToString("hh':'mm")
// or
ToString(@"hh\:mm")
同时检查所有可用的格式,这里http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
var test = dataRow.Field<TimeSpan>("fstart").ToString("hh.mm");
//test ="08:00"
var tb = (TextBox) gridViewRow.Cells[2].FindControl("fstart");
tb.Text = test;
以前的解决方案不运行,如果小时> 24,如果你在几分钟内非常大的有时间尝试此解决方案
int minutes = 159000;
TimeSpan t = new TimeSpan(0, minutes, 0);
String HOURS = Math.Round(t.TotalHours, 0).ToString();
if (HOURS.Length==1)
{
HOURS = "0"+HOURS;
}
String MINUTES = t.Minutes.ToString();
if (MINUTES.Length == 1)
{
MINUTES = "0" + MINUTES;
}
String RESULT = HOURS + ":" + MINUTES;
你可以做到这一点:
var hhmm = TimeSpan.FromMinutes(minutes).ToString(@"hh\:mm")