我有像相对datetime
字符串:转换相对日期时间字符串到DateTime对象
- “5分钟前”
- “10个小时前”
- “4天前” 等
如何将其转换为确切的datetime
,正好相反this question
我有像相对datetime
字符串:转换相对日期时间字符串到DateTime对象
如何将其转换为确切的datetime
,正好相反this question
此代码应工作:
string input = "10 days ago";
DateTime result = DateTime.MinValue;
int minutesMultiplier = 0;
if (input.Contains("minute"))
minutesMultiplier = 1;
else
if (input.Contains("hour"))
minutesMultiplier = 60;
else
if (input.Contains("day"))
minutesMultiplier = 1440;
else
throw new Exception("Couldn't parse time format");
string numberStr = input.Split(' ')[0];
int number;
if (int.TryParse(numberStr, out number))
result = DateTime.Now.AddMinutes(-number * minutesMultiplier);
它做的间隔名称解析(如分钟,小时,日)和它们相乘得到的分钟数,因为后来它使用DateTime.Now.AddMinutes
方法,同样的事情可以使用TimeSpan
完成,并调用DateTime.Now.Add
。
这里是一个处理包含多个间隔名称的字符串的情况下,如“10小时15分钟前”一个例子:
// If there are mixed interval types in an input string
string input = "10 days and 10 hours ago";
// Parse out the intervals and numbers
var matches = Regex.Matches(input,
@"(?<number>\d+)\s(?<interval>(day)|(minute)|(hour))");
// Convert them to dictionary
var dic = matches
.Cast<Match>()
.ToDictionary(
key => key.Groups["interval"].Value,
o => int.Parse(o.Groups["number"].Value));
// Calculate the total number of minutes for each interval
DateTime result = DateTime.MinValue;
int totalMinutes = 0;
foreach (var keyValue in dic)
{
if (keyValue.Key.Contains("minute"))
totalMinutes += keyValue.Value;
else
if (keyValue.Key.Contains("hour"))
totalMinutes += keyValue.Value * 60;
else
if (keyValue.Key.Contains("day"))
totalMinutes += keyValue.Value * 1440;
else
throw new Exception("Unparsable time format");
}
result = DateTime.Now.AddMinutes(-totalMinutes);
请注意,此代码依赖正确格式化的输入字符串。 – 2012-08-17 09:27:56
是的,推定是输入是可预测的并可能自动生成。 – 2012-08-17 09:30:55
'string input =“10小时30分钟前”;' - 你的代码是做什么的?我知道你不能预见所有可能的输入,但是当输入不符合你期望的格式时,你应该抛出一个异常,而不是默默地做错误的事情。 – hvd 2012-08-17 09:48:15
正确的方法是将您的相对值存储为TimeSpan
值,并从DateTime.Now
(或您希望用作基准的任何DateTime
)中减去该值。
您可以使用诸如int.Parse
之类的方法将数字(分钟数,小时数等)转换为整数值并将其复制到您的TimeSpan
值中。确切的解析算法取决于您的字符串的实际格式,即允许哪些单词出现,以及按什么顺序出现这些数字。
如果如你的问题的字符串已经隔离,你可以尝试使用正则表达式(与Regex
class)拆卸他们:
^(\d+)\s+([a-z]+)\s+ago$
你需要编写自己的程序这样做就像做相反的人必须做的一样。基本上,您将需要解析文本以查找间隔(即分钟数,小时数,天数等),金额以及它是过去还是未来(使用ago
或from
)。
此时,您将拥有足够的数据构建适当的TimeSpan
实例,并将其与DateTime.Now
一起使用以获得该时间。
为了达到上述目的,您需要确保要解析的字符串值是标准化的。
的[聪明的方式来解析日期C#可能的复制](http://stackoverflow.com/questions/14583285/clever-way-to-parse-dates-c-sharp) – 2016-07-03 04:39:19