【问题标题】:library to parse a relative date (like google calendar can) in c# [closed]在c#中解析相对日期(如谷歌日历可以)的库[关闭]
【发布时间】:2022-05-13 03:15:21
【问题描述】:

我问的是同样的问题:How can I parse relative dates with Perl? 但在 C# 中。

对不起,如果这是重复的,如果是这样,请删除。

这样的库存在吗?

谢谢

【问题讨论】:

标签: c# datetime text-parsing


【解决方案1】:
using System;
using System.Text.RegularExpressions;

class RelativeDateParser
    {
        
        public static DateTime Parse(string input)
        {
            DateTime dt = DateTime.Now;

            // parse "x days x hours x minutes x seconds" or "x days x hours x minutes x seconds ago"
            Regex r = new Regex("(day)|(hour)|(minues)|(second)");
            if (r.Match(input).Success == true)
            {
                dt = ParseDHMS(input, dt);
            }

            // parse "yesterday" or "today" or "tomorrow" or "eow" or "eod"
            r = new Regex("(today)|(tomorrow)|(eow)|(eod)");
            if (r.Match(input).Success == true)
            {
                dt = ParseGenericRelative(input);
            }

            Console.WriteLine("Now DateTime: " + DateTime.Now.ToString());
            Console.WriteLine("New DateTime: " + dt.ToString());
            return dt;
        }

        private static DateTime ParseGenericRelative(string input)
        {
            throw new NotImplementedException("Not implemented");
        }
        
        private static DateTime ParseDHMS(string input, DateTime seedDtm)
        {
            TimeSpan timeSpan = new TimeSpan(0);
            
            // search for days
            timeSpan += TimeSpan.FromDays(getMetricValue(input, "day"));
            // search for hours
            timeSpan += TimeSpan.FromHours(getMetricValue(input, "hour"));
            // search for minutes
            timeSpan += TimeSpan.FromMinutes(getMetricValue(input, "minutes"));
            // search for seconds
            timeSpan += TimeSpan.FromSeconds(getMetricValue(input, "second"));
            
            return seedDtm.AddTicks(timeSpan.Ticks * (int)(input.EndsWith("ago") ? -1 : 1));
        }
        
        private static double getMetricValue(string input, string metric)
        {
            Regex r = new Regex(@"(\d+)\s*" + metric);
            Match m = r.Match(input);
            if (m.Success)
            {
                string match = m.Groups[1].Value;
                return Double.Parse(match);
            }
            
            return 0;
        }
    }

Wayback Machine copy of original solution
注意:此实现尚未经过测试

【讨论】:

  • 链接已损坏
  • @MichaelFreidgeim 我设法找到了原始代码。请注意,此代码尚未经过测试
猜你喜欢
  • 2014-09-03
  • 2012-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-02
  • 1970-01-01
  • 2015-01-21
相关资源
最近更新 更多