我有像这样的字符串: '1小时' '5分钟' '1天' '30秒' '4小时'
这个字符串表示自某事以来的过去时间。 我想将它们转换为它发生的时间(DateTime)
我试图将它插入到timespan.parse中,但它会抛出异常......
做这样的事情的最佳方式是什么?
由于
答案 0 :(得分:2)
您可以尝试使用 Dictionary 来使用所有名称:
public static TimeSpan ParseTimeSpan(String value) {
// Expand dictionary with values you're using, e.g.
// "second", "minute", "week" etc.
Dictionary<String, long> seconds = new Dictionary<String, long>() {
{"days", 86400},
{"day", 86400},
{"hours", 3600},
{"hour", 3600},
{"mins", 60},
{"min", 60},
{"secs", 1},
{"sec", 1}
};
String[] items = value.Split();
long result = 0;
for (int i = 0; i < items.Length - 1; i += 2)
result += long.Parse(items[i]) * seconds[items[i + 1]];
return TimeSpan.FromSeconds(result);
}
...
TimeSpan result = ParseTimeSpan("1 hour 15 mins 32 secs");
答案 1 :(得分:0)
字符串中的第二部分是单位。
Dunno关于格式化你将拥有的内容,但所有这些内容都可以像这样拆分和解析:
// text is "1 hour" or "5 mins" or "1 day" or "30 secs" or "4 hours"
var item = text.Split(new char[] {' '});
var value = int.Parse(item[0]);
var unit = item[1];
// get lowest units, in our case it is seconds
if(unit.StartWith("min"))
value *= 60;
else
if(unit.StartWith("hour"))
value *= 60 * 60;
else
if(unit.StartWith("day"))
value *= 60 * 60 * 24;
// now that we have seconds, we can convert it into timespan
var timespan = new TimeSpan(0, 0, value);
您可以为 ms 甚至 ticks 执行此操作。
答案 2 :(得分:0)
string strResultTime = "5 hours";
//The function that gets the time and converts it to seconds
MatchEvaluator evaluator = new MatchEvaluator(ConvertToSeconds);
strResultTime = Regex.Replace(strResultTime, "(?<num>\\d+?) (?<timeUnit>.+)", evaluator);
//Parse the seconds to an actual datetime.
DateTime indexTime = DateTime.Now.AddSeconds(int.Parse(strResultTime) * -1);
/// <summary>
/// Converts strings if format 'X time' like '2 mins' or '5 hours' to the time that they represents in seconds
/// </summary>
/// <param name="mchTime">Match that contains '2 mins' and Groups["timeUnit"] = 'hour' or other time unit AND Groups["num"] = the number of that time unit</param>
/// <returns>The number of seconds as string</returns>
private string ConvertToSeconds(Match mchTime)
{
//Switch on the time unit
switch (mchTime.Groups["timeUnit"].Value)
{
case "day":
case "days":
//Return the number of days as seconds
return (int.Parse(mchTime.Groups["num"].Value) * 24 * 60 * 60).ToString();
case "hour":
case "hours":
//Return the number of hours as seconds
return (int.Parse(mchTime.Groups["num"].Value) * 60 * 60).ToString();
case "min":
case "mins":
//Return the number of mins as seconds
return (int.Parse(mchTime.Groups["num"].Value) * 60).ToString();
case "sec":
case "secs":
return mchTime.Groups["num"].Value;
default:
throw new NotImplementedException();
}
}
答案 3 :(得分:0)
DateTime.Parse has an overloaded version that allows you to pass an `IFormatProvider`. Creating a class that implements `IFormatProvider` to convert your strings how you want them parsed, and pass an instance of this class to `TimeSpan.Parse` as a second argument. This would be the approach I would take.
答案 4 :(得分:-2)
使用类似“1:5”的字符串和TimeSpan.TryParse