0

I'd like to format some text in a string. So if I input the text 0759, it should format it to 07:59 (minutes and seconds).

Same it should work like this (pseudocode)

input 759 -> output 07:59

input 10545 -> output 01:05:45 (hours, minutes, seconds)

input 5 -> output 00:05

I thought about using string.Format() but I as a newbie I don't really know how to do that.

Thanks!

4

4 回答 4

1

你必须跳过几个不同的圈才能完成这项工作。您需要将您的数字转换为字符串,并将它们填充适当数量的位置 (6)。然后您必须使用适当的信息调用 DateTime.ParseExact。下面的代码应该适用于您需要的一切:

void Main()
{

var i = 10545;
var t = i.ToString().PadLeft(6, '0');

var d = DateTime.ParseExact(t, "HHmmss", System.Globalization.CultureInfo.InvariantCulture );

Console.WriteLine(string.Format("{0:HH:mm:ss}", d));
}

您需要使用 24 小时格式来获得所需的确切小时、分钟、秒。超过 235959 的任何内容都会出错,因此您必须以不同的方式处理它。

请参阅DateTime.ParseExact() 的文档和格式代码的文档

于 2013-08-30T15:30:23.587 回答
1

您可以使用此方法:

public static TimeSpan? TryParseTimeSpan(string input)
{
    TimeSpan? ts = (TimeSpan?)null;
    if (!string.IsNullOrWhiteSpace(input))
    {
        input = input.Trim();
        int length = input.Length % 2 == 0 ? input.Length : input.Length + 1;
        int count = length / 2;

        if(count > 3) return null;

        input = input.PadLeft(count * 2, '0');

        string[] validFormats = new[] { "HHmmss", "mmss", "ss" };
        DateTime dt;
        if (DateTime.TryParseExact(input, validFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
            ts = dt.TimeOfDay; 
    }
    return ts;
}

但是,它不接受 89 秒的第二部分,这不是有效的输入(恕我直言)。

使用此示例输入进行测试:

List<string> inputs = new List<string> { "78", "10545", "5" };
IEnumerable<TimeSpan> timeSpans = inputs
    .Select(i => TryParseTimeSpan(i))
    .Where(ts => ts.HasValue)
    .Select(ts => ts.Value);
foreach (TimeSpan ts in timeSpans)
    Console.WriteLine(ts.ToString());

DEMO

输出:

01:05:45
00:00:05
于 2013-08-30T15:31:00.543 回答
1
List<string> inputs = new List<string> { "78", "10545", "5" };
IEnumerable<TimeSpan> timeSpans = inputs
    .Select(i => TryParseTimeSpan(i))
    .Where(ts => ts.HasValue)
    .Select(ts => ts.Value);
foreach (TimeSpan ts in timeSpans)
    Console.WriteLine(ts.ToString());
于 2017-07-04T10:06:00.813 回答
0

首先,您需要为 00:00 配置您想要使用格式字符串的格式"00:00"

string input = 0789
input = String.Format("00:00",input); //input is now 07:89

但是,这不适用于超过 4 位的值。使用TimeSpan对象将是处理这些的更好方法,因为它们已经具有分钟和秒组件

时间跨度:http: //msdn.microsoft.com/en-us/library/system.timespan.aspx

格式来源:http: //msdn.microsoft.com/en-us/library/system.string.format.aspx

于 2013-08-30T15:18:42.883 回答