I've see
this post. What if my string is string x = "Tomorrow 04-26-19 09:14AM sunrise.";
, basically the datetime value is always in mm-dd-yy hh:mm<AM/PM>
format. So I'd need to extract this value of 04-26-19 09:14AM
and remember the starting position which = 9.

- 6,272
- 6
- 49
- 87
-
Does it always occur after the first space and end before the last one. Otherwise, use a simple Regex to pick out the match, and then do a second pass using `string.IndexOf` (unless you need to do a million of these operations) – Flydog57 Jul 22 '20 at 01:31
-
@Flydog57 - Even with a million operations your suggestion sounds quite fast. – Enigmativity Jul 22 '20 at 01:46
-
@Flydog57 - Regex matches keep index anyway. So actually quite fast. – Enigmativity Jul 22 '20 at 01:49
2 Answers
This works nicely for me:
string x = "Tomorrow 04-26-19 09:14AM sunrise.";
var regex = new Regex(@"\d{2}-\d{2}-\d{2} \d{2}:\d{2}(AM|PM)");
var match = regex.Match(x);
if (match.Success)
{
var prefix = x.Substring(0, match.Index);
var value = DateTime.ParseExact(match.Value, "MM-dd-yy hh:mmtt", System.Globalization.CultureInfo.CurrentCulture);
var suffix = x.Substring(match.Index + match.Length);
}
It's using Regex
to find a potential DateTime
string and then determines the prefix part of the string, the DateTime
value, and the suffix part of the string.
It gives me:
"Tomorrow "
2019/04/26 09:14:00
" sunrise."

- 113,464
- 11
- 89
- 172
If "tomorrow" and "sunshine" aren't necessarily always going to be present in a string like x but the format of this string will be similar, I'd probably split these strings according to the space character like this.
x.Split(' ')
with indices
string strDate = x.Split(' ')[1];
string strTime = x.Split(' ')[2];
& then join those sets of strings
string dt = $"{strDate} {strTime}";
& then probably use the DateTime.ParseExact functionality to craft an actual DateTime object out of what I parsed.
DateTime.ParseExact(dt, "MM-dd-yy hh:mmtt", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeLocal)
I generally use assumelocal so that I know the time won't be UTC. "tt" is a placeholder for AM or PM.
If this is something you'll have to do iteratively, then I would probably create a method for this, and then simply call it routinely.

- 9
- 1
- 1
- 4