Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4110754
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T21:58:30+00:00 2026-05-20T21:58:30+00:00

Is there an equivalent of PHP’s strtotime() function working on .NET Framework. I’m talking

  • 0

Is there an equivalent of PHP’s strtotime() function working on .NET Framework. I’m talking about it’s capacity to handle strings likes:

  • strtotime(“now“)
  • strtotime(“10 September 2000”)
  • strtotime(“+1 day“)
  • strtotime(“+1 week“)
  • strtotime(“+1 week 2 days 4 hours 2 seconds“)
  • strtotime(“next Thursday“)
  • strtotime(“last Monday“)

Obviously DateTime.Parse() and Convert.ToDateTime() don’t do that.

The closest I’ve found is a small class which only handles a few of those: http://refactormycode.com/codes/488-parse-relative-date

EDIT: I’m not interested in C# compile-time features. The problem is converting human relative date/time strings to DateTime at runtime (i.e., “now” –> DateTime.Now and such).

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T21:58:31+00:00Added an answer on May 20, 2026 at 9:58 pm

    As so far there is no answer, I made it based on the example given. It supports most cases except those like “last Thurday” (or other days of the week).

    /// <summary>
    /// Parse a date/time string.
    /// 
    /// Can handle relative English-written date times like:
    ///  - "-1 day": Yesterday
    ///  - "+12 weeks": Today twelve weeks later
    ///  - "1 seconds": One second later from now.
    ///  - "5 days 1 hour ago"
    ///  - "1 year 2 months 3 weeks 4 days 5 hours 6 minutes 7 seconds"
    ///  - "today": This day at midnight.
    ///  - "now": Right now (date and time).
    ///  - "next week"
    ///  - "last month"
    ///  - "2010-12-31"
    ///  - "01/01/2010 1:59 PM"
    ///  - "23:59:58": Today at the given time.
    /// 
    /// If the relative time includes hours, minutes or seconds, it's relative to now,
    /// else it's relative to today.
    /// </summary>
    internal class RelativeDateParser
    {
        private const string ValidUnits = "year|month|week|day|hour|minute|second";
    
        /// <summary>
        /// Ex: "last year"
        /// </summary>
        private readonly Regex _basicRelativeRegex = new Regex(@"^(last|next) +(" + ValidUnits + ")$");
    
        /// <summary>
        /// Ex: "+1 week"
        /// Ex: " 1week"
        /// </summary>
        private readonly Regex _simpleRelativeRegex = new Regex(@"^([+-]?\d+) *(" + ValidUnits + ")s?$");
    
        /// <summary>
        /// Ex: "2 minutes"
        /// Ex: "3 months 5 days 1 hour ago"
        /// </summary>
        private readonly Regex _completeRelativeRegex = new Regex(@"^(?: *(\d) *(" + ValidUnits + ")s?)+( +ago)?$");
    
        public DateTime Parse(string input)
        {
            // Remove the case and trim spaces.
            input = input.Trim().ToLower();
    
            // Try common simple words like "yesterday".
            var result = TryParseCommonDateTime(input);
            if (result.HasValue)
                return result.Value;
    
            // Try common simple words like "last week".
            result = TryParseLastOrNextCommonDateTime(input);
            if (result.HasValue)
                return result.Value;
    
            // Try simple format like "+1 week".
            result = TryParseSimpleRelativeDateTime(input);
            if (result.HasValue)
                return result.Value;
    
            // Try first the full format like "1 day 2 hours 10 minutes ago".
            result = TryParseCompleteRelativeDateTime(input);
            if (result.HasValue)
                return result.Value;
    
            // Try parse fixed dates like "01/01/2000".
            return DateTime.Parse(input);
        }
    
        private static DateTime? TryParseCommonDateTime(string input)
        {
            switch (input)
            {
                case "now":
                    return DateTime.Now;
                case "today":
                    return DateTime.Today;
                case "tomorrow":
                    return DateTime.Today.AddDays(1);
                case "yesterday":
                    return DateTime.Today.AddDays(-1);
                default:
                    return null;
            }
        }
    
        private DateTime? TryParseLastOrNextCommonDateTime(string input)
        {
            var match = _basicRelativeRegex.Match(input);
            if (!match.Success)
                return null;
    
            var unit = match.Groups[2].Value;
            var sign = string.Compare(match.Groups[1].Value, "next", true) == 0 ? 1 : -1;
            return AddOffset(unit, sign);
        }
    
        private DateTime? TryParseSimpleRelativeDateTime(string input)
        {
            var match = _simpleRelativeRegex.Match(input);
            if (!match.Success)
                return null;
    
            var delta = Convert.ToInt32(match.Groups[1].Value);
            var unit = match.Groups[2].Value;
            return AddOffset(unit, delta);
        }
    
        private DateTime? TryParseCompleteRelativeDateTime(string input)
        {
            var match = _completeRelativeRegex.Match(input);
            if (!match.Success)
                return null;
    
            var values = match.Groups[1].Captures;
            var units = match.Groups[2].Captures;
            var sign = match.Groups[3].Success ? -1 : 1;
            Debug.Assert(values.Count == units.Count);
    
            var dateTime = UnitIncludeTime(units) ? DateTime.Now : DateTime.Today;
    
            for (int i = 0; i < values.Count; ++i)
            {
                var value = sign*Convert.ToInt32(values[i].Value);
                var unit = units[i].Value;
    
                dateTime = AddOffset(unit, value, dateTime);
            }
    
            return dateTime;
        }
    
        /// <summary>
        /// Add/Remove years/days/hours... to a datetime.
        /// </summary>
        /// <param name="unit">Must be one of ValidUnits</param>
        /// <param name="value">Value in given unit to add to the datetime</param>
        /// <param name="dateTime">Relative datetime</param>
        /// <returns>Relative datetime</returns>
        private static DateTime AddOffset(string unit, int value, DateTime dateTime)
        {
            switch (unit)
            {
                case "year":
                    return dateTime.AddYears(value);
                case "month":
                    return dateTime.AddMonths(value);
                case "week":
                    return dateTime.AddDays(value * 7);
                case "day":
                    return dateTime.AddDays(value);
                case "hour":
                    return dateTime.AddHours(value);
                case "minute":
                    return dateTime.AddMinutes(value);
                case "second":
                    return dateTime.AddSeconds(value);
                default:
                    throw new Exception("Internal error: Unhandled relative date/time case.");
            }
        }
    
        /// <summary>
        /// Add/Remove years/days/hours... relative to today or now.
        /// </summary>
        /// <param name="unit">Must be one of ValidUnits</param>
        /// <param name="value">Value in given unit to add to the datetime</param>
        /// <returns>Relative datetime</returns>
        private static DateTime AddOffset(string unit, int value)
        {
            var now = UnitIncludesTime(unit) ? DateTime.Now : DateTime.Today;
            return AddOffset(unit, value, now);
        }
    
        private static bool UnitIncludeTime(CaptureCollection units)
        {
            foreach (Capture unit in units)
                if (UnitIncludesTime(unit.Value))
                    return true;
            return false;
        }
    
        private static bool UnitIncludesTime(string unit)
        {
            switch (unit)
            {
                case "hour":
                case "minute":
                case "second":
                    return true;
    
                default:
                    return false;
            }
        }
    }
    

    I’m sure there are improvements possible but it should handle most cases in English. Please comment if you see improvements (like locale errors or such).

    EDIT: Fixed to be relative to now if the relative time includes time.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm wondering if there is an ASP.Net MVC equivalent to PHP's require_once() function. Lets
I'm wondering if there is an equivalent function to PHP's call_user_func() in ASP.NET application.
Is there an C# equivalent to the PHP function parse_str ? I couldn't find
Is there any equivalent function that returns the character at position X in PHP?
Is there an equivalent to Perl's format function in PHP? I have a client
Is there a PHP equivalent function to the Python os.path.normpath() ? Or how can
Python has a nice zip() function. Is there a PHP equivalent?
Is there an equivalent of PHP's highlight_string function in C#? It is not necessary
Is there an equivalent in JavaScript for PHP's reference passing of variables? [PHP]: function
Is there any shortcut to accomplishing the equivalent of PHP's array_flip function in JavaScript

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.