WelcomeUser Guide
ToSPrivacyCanary
DonateBugsLicense

©2024 Poal.co

1.0K

C#

Trying to get a date out of a string. For some reason this is not working. Could be I'm tired and just don't see it. The date it should get is 2017-10-05 but it does not detect a date at all.

file = "171005_010"

f = Regex.Replace(file, "[^0-9]", "");
if (f.Length >= 6)
{
    try
    {
        bool z = DateTime.TryParseExact(f.Substring(0, 6), "yyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result);
        string y = result.ToString();
        if (z)
        {
            return result.ToString(dateformat);
        }
    }
    catch (Exception ee)
    {
        return null;
    }
}





EDIT

Found the problem.

changed

f = Regex.Replace(file, "[^0-9]", "");

to

f = Regex.Replace(f, "[^0-9]", "");

file did NOT = "171005_010"

Almost never fails. Just have to ask before I figure it out.

C# Trying to get a date out of a string. For some reason this is not working. Could be I'm tired and just don't see it. The date it should get is 2017-10-05 but it does not detect a date at all. ``` file = "171005_010" f = Regex.Replace(file, "[^0-9]", ""); if (f.Length >= 6) { try { bool z = DateTime.TryParseExact(f.Substring(0, 6), "yyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime result); string y = result.ToString(); if (z) { return result.ToString(dateformat); } } catch (Exception ee) { return null; } } ``` EDIT Found the problem. changed `f = Regex.Replace(file, "[^0-9]", "");` to `f = Regex.Replace(f, "[^0-9]", "");` file did NOT = "171005_010" Almost never fails. Just have to ask before I figure it out.

(post is archived)

[–] 1 pt

ok, i know this is old and you have a solution, but I am bored and looked into this anyway :)

I really like to keep things simple, so there is no real need for the Regex or for the DateTime:

f = "171005_010"; //assuming this is ALWAYS the format

try {
    //if f is shorter than 6, one of these substring will throw an exception
    string yy = f.Substring(0, 2);
    string mm = f.Substring(2, 2);
    string dd = f.Substring(4, 2);
    
    //since there is only a 2-digit year in f, must assume only 20xx in set
    return "20" + yy + "-" + mm + "-" + dd;
} catch (ArgumentOutOfRangeException ee) {
    return null;
}
[–] 0 pt

U kant code amd u been on dah blogs to long mane

[+] [deleted] 1 pt