最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - TimeSpan remove seconds - Stack Overflow

programmeradmin0浏览0评论

How do you truncate the seconds bit from a timespan object in C#? i.e. 15:37

I'm outputting a timespan object to JavaScript in the format of HH:mm and kind of want the server side to process providing the correct format instead of clients browsers, can that be done without providing this as a C# string object to JavaScript?

How do you truncate the seconds bit from a timespan object in C#? i.e. 15:37

I'm outputting a timespan object to JavaScript in the format of HH:mm and kind of want the server side to process providing the correct format instead of clients browsers, can that be done without providing this as a C# string object to JavaScript?

Share Improve this question asked Feb 24, 2011 at 22:44 MayaMaya 1,4125 gold badges23 silver badges44 bronze badges 6
  • If you're formatting the timespan as HH:mm aren't the seconds already truncated? – Chris Van Opstal Commented Feb 24, 2011 at 22:46
  • Do you really want to set the seconds to 0 in a TimeSpan, or just omit them when converting to string? – CodesInChaos Commented Feb 24, 2011 at 22:46
  • Have a look at this answer stackoverflow.com/questions/338658/… – Will Dean Commented Feb 24, 2011 at 22:52
  • @CodeInChaos @fredrik-mork @Nick Yes omit the seconds without converting to string, my JSON serializer will need to get hh:mm in TimeSpan format without converting to String – Maya Commented Feb 24, 2011 at 22:53
  • 1 @Maya: a TimeSpan is a value, not a string representation of a value. If you need it in a specific format, you will need to convert it to a string. – Fredrik Mörk Commented Feb 24, 2011 at 23:04
 |  Show 1 more comment

5 Answers 5

Reset to default 20

You can use a format string for that:

public string GetTimeSpanAsString(TimeSpan input)
{
    return input.ToString(@"hh\:mm");
}

You can truncate the 'ticks' value which is the core of a TimeSpan:

TimeSpan t1 = TimeSpan.FromHours(1.551);
Console.WriteLine(t1);
TimeSpan t2 = new TimeSpan(t1.Ticks - (t1.Ticks % 600000000));
Console.WriteLine(t2);

Gives:

01:33:03.6000000
01:33:00

Maybe not optimal, but easy to read:

TimeSpan.FromMinutes((long)duration.TotalMinutes);

I believe this is what you're looking for.

string.Format("{0:H:mm}",myTime)

Perhaps something like this. This truncates to minutes using the truncation of an integer division, followed by a multiplication by the divisor.

return TimeSpan.FromTicks(input.Ticks/TicksPerMinute*TicksPerMinute);
发布评论

评论列表(0)

  1. 暂无评论