如何实现时间跨度到字符串的转换?
我尝试在此处搜索,但它对我没有多大帮助..
我想转换 time_span 为字符串,我不想返回以天为单位的时间跨度..而只想返回 HH:mm:ss。如何实现这一目标?
我的示例代码在这里:
String time_span_par = "06:12:40";
String time_str = "18:13:59";
TimeSpan time_span_var = TimeSpan.Parse(time_span_par);
TimeSpan time_span = TimeSpan.Parse(time_str);
time_span = time_span.Add(time_span_var);
string temp = time_span.ToString("HH:mm:ss");
I tried searching here, but it couldn't help me much ..
I want to convert time_span to string, I don't want to return the timespan in days .. but only HH:mm:ss. How to achieve that?
My sample code is here:
String time_span_par = "06:12:40";
String time_str = "18:13:59";
TimeSpan time_span_var = TimeSpan.Parse(time_span_par);
TimeSpan time_span = TimeSpan.Parse(time_str);
time_span = time_span.Add(time_span_var);
string temp = time_span.ToString("HH:mm:ss");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
尝试使用
Try using
这应该有效:
根据评论,如果您想要两位数,您可以这样做:
编辑:根据吉米的评论,
This should work:
As per comment if you want the double digits you could do:
Edited:as per jimmy's comment,
试试这个:
编辑
在我阅读了您对问题的评论后,即您需要在新的日子中显示零小时,我的答案将为您提供总小时数、分钟数和秒数,而不是您想要的。
(+1) 凯尔西斯;)
Try this:
Edit
After I read your comment on your question, that is you need to display zero hours for new days, my answer will give you total hours, minutes and seconds, not what you want.
(+1) Kelseys ;)
我实现的代码是:
最初由 Marc Gravell 发布,
The code I have implemented is:
Originally posted by Marc Gravell,
现在有一种更简单的方法可以做到这一点(尽管只使用框架 4),您只需要按字面意思使用字符串,并且可以直接在 TimeSpan 实例上执行此操作。
这将输出
Helpful now 对于那些偶然发现这个问题的人(比如我自己)。
干杯:)
There is a much simpler way of doing this now (albeit only using framework 4), you just need to use the string literally, and you can do it directly on the TimeSpan instance.
That will output
Helpful now for people stumbling across this (like myself).
Cheers :)
只需将刻度值转换为 DateTime,然后使用其 ToString()
Simply convert the value of ticks into a DateTime and then use its ToString()
如果天数不相关,那么您就有了解决方案,但是我在寻找总共提供小时数的转换时遇到了这个答案,因此 36 小时需要显示为 36:00:00。使用上面的一些提示,这就是我想到的:
总小时数始终向下舍入,分钟和秒填充为 2 位数字 (00 - 09)
If the number of days is irrelevant then you have the solution, however I came across this answer searching for a conversion that gave hours in total, so 36 hours would need to be displayed as 36:00:00. Using some of the hints above this is what I came up with:
Total Hours is always rounded down, minutes and seconds are padded to be 2 digits (00 - 09)