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).
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).
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.
The DateTime struct has several methods and properties to get what you need:
If the functionality provided by the DateTime struct isn't enough, I'd suggest checking out the noda-time project (by Jon Skeet).
etc etc
I think you'll have to write your own method.
"now" is just
DateTime.Now
."+1 day" would be
DateTime.Now.AddDays(1)
for example.So you'll need to parse your string looking for this type of input and then call the appropriate
DateTime
method. The fall-through case would be to pass the string throughDateTime.Parse(String, IFormatProvider, DateTimeStyles)
with different DateTimeStyles.I think the 'correct' answer here is to use something like https://github.com/robertwilczynski/nChronic. It's a port of the Ruby equivalent and can parse a wide range of date time formats, as listed here: http://chronic.rubyforge.org/ in the 'Examples' section (scroll down).
I think the best way this to write extension methods to DateTime to handle your needs.
Maybe, it can be OSS, so the community can help you to implement it.