1

So I have a program I use that I have become very intrigued by how they force their formatting of a date in a field when input. For example, if I put in "10217", the system would automatically force the field to become 10/02/2017. However, if I put in 1117, then nothing happens as it could be 01/01/2017, 11/17/??, or some other of many combinations. Does anyone know how this forced formatting might be being achieved regarding the logic?

Additionally, you can put in a date in the same field formatted as 10.2.17 and it would reformat to 10/2/2017. As well, if you input 1.1.17, it would reformat to 1/1/2017. Lastly, you can do the same thing of putting in the slashes and it will reformat the respective date format. So if I put in 10/2/17, it would reformat to 10/2/2017. Same this with typing 1/1/17 will reformat to 1/1/2017.

I've looked at the following link, but am not seeing anything that could be used to do this kind of logic. (Granted I could just be blatantly missing it.)

https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

As well, I have seen this example surrounding a regex, but I am not familiar with this process.

Validating a date format string in c#

I understand this is a lot, but this all revolves around the date forced formatting logic. I am really not sure what logic to use to achieve what I want or what logic to chain together to achieve what I am looking for. I greatly appreciate all of the input.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • Most likely is is parsing the input to a date, then formatting the date using a specific format, then setting the value of the text box. There's no "magic bullet" in C# to do it all in one step. _Exactly_ how it's done depends on the platform (c# server side, javaScript client-side, etc.). There may also be some logic to "guess" when the date is ambiguous (e.g. 10/2/2017). – D Stanley Dec 11 '17 at 22:54
  • Alright. That makes sense. I do see now how there might be too many variables to how it is done. Granted I can say it is done client site, the software is in c#/.net, but I haven't seen any JavaScript that I am aware of. I will have to look for it. Do you have any simple or suggestions on how to handle this? I wasn't sure what methods we could utilize that would parse the text for us or if I needed to code all cases I can find. (NOTE: I am trying to replicate this with a software I am developing.) – Ryan Wakefield Dec 11 '17 at 23:52

1 Answers1

1

I think to approach this problem it may be necessary to see what they are using to parse the input of the user. If they are using DateTime.Parse then it will throw an exception when the string being parsed is ambiguous.

Of course, a programmer could always create their own way of parsing the input in the field. Though, typically a programmer isn't that enthusiastic about dealing with the ambiguous cases when parsing information. So let's assume they are working with a DateTime.Parse method for simplicity sake.

I created the following program to allow you to see when the parser sees something as ambiguous. The output of the program is shown in this picture:

enter image description here

The code demonstrating DateTime.Parse:

static void Main(string[] args)
{
    string input = "";
    while(input != "exit" || input != "Exit")
    {
        Console.Write("Input: ");
        input = Console.ReadLine();

        string inputDate = input;
        //try to parse it
        try
        {
            DateTime date = DateTime.Parse(inputDate);
            Console.WriteLine(date+"\n");
        }
        catch
        {
            //Exceptions. String not valid because ambiguity
            Console.WriteLine("Ambiguous.\n");
            //In here can also perform other logic, of course
        }

    }

}

In order to convert the DateTime back to a string you can do something similar to:

try
{

    DateTime date = DateTime.Parse(inputDate);
    Console.WriteLine(date+"\n");
    string month = date.Month.ToString();
    string day = date.Day.ToString();
    string year = date.Year.ToString();
    string resultingString = month + " " + day + " " + year ;
    Console.WriteLine(resultingString);
}
catch(Exception e)
{
    //Exceptions. String not valid because ambiguity
    Console.WriteLine("Ambiguous");
}

You can even make your own parser with this information in this fashion so you can acheive a result for a date entered that is 3 characters long:

    static void Main(string[] args)
    {
        string input = "";
        while(input != "exit" || input != "Exit")
        {
            Console.Write("Input: ");
            input = Console.ReadLine();

            string inputDate = input;

            try
            {

                DateTime date = DateTime.Parse(inputDate);
                Console.WriteLine(date+"\n");
                string month = date.Month.ToString();
                string day = date.Day.ToString();
                string year = date.Year.ToString();
                string resultingString = month + " " + day + " " + year;
                //string resultingString = month + "/" + day + "/" + year;
                Console.WriteLine(resultingString);
            }
            catch(Exception e)
            {
                //Exceptions. String not valid because ambiguity
                try
                {
                   Console.WriteLine( myParser(inputDate) );
                }
                catch
                {
                    Console.WriteLine("Ambiguous");
                }

                //Console.WriteLine("Ambiguous.\n");
                //In here can also perform other logic, of course
            }

        }

    }

    static string myParser(string input)
    {
        string month,day,year,date;

        switch (input.Length)
        {
            //In the case that it's 1 character in length 
            case 1:
                return "Ambiguous.";
            case 2:
                return "Ambiguous.";

            //did user mean #/#/200#?  hopefully not #/#/199#...
            case 3:
                month = input.Substring(0, 1);
                day = input.Substring(1, 1);
                year = input.Substring(2, 1);
                date = month + " " + day + " " + year;
                return date;
            //did user mean  # # 20## 
            //or             # ## 200# 
            //or             ## # 200#
            case 4:

                return "Ambiguous";
            //user probably means ## # ##
            case 5:
                return "Ambiguous";
            case 6:
                return "Ambiguous";
            default:
                return "Ambiguous";
        }


    }

enter image description here

Similarly, if you want to get the date back to a slash (/) seperated format in the form of a string without the minutes and hours and such..

case 3:
    month = input.Substring(0, 1);
    day = input.Substring(1, 1);
    year = input.Substring(2, 1);
    date = month + " " + day + " " + year;

    DateTime dateTimeObj = DateTime.Parse(date);

    month = dateTimeObj.Month.ToString();
    day = dateTimeObj.Day.ToString();
    year = dateTimeObj.Year.ToString();

    string resultingString = month + "/" + day + "/" + year;

    return resultingString;

enter image description here

Jamin
  • 1,362
  • 8
  • 22
  • I believe this is what they are using as the output is exactly what I am looking for. Too expand on what you did here, is there a way to not show the time? To restrict it too just the date in that format? I looked for the option but I didn't see it. As well, I think my code will force it to go back in the box until a valid parsable string is input. Thanks – Ryan Wakefield Dec 12 '17 at 03:07
  • @RyanWakefield I hope this is kind of approach to the parsing behavior you were looking for. – Jamin Dec 12 '17 at 03:24
  • @RyanWakefield Sorry I edited again to show extra parsings....Shame on me. Also date entries can get tricky so it's important to do implementation checking and just basic testing to see if you are getting the parsed information you want. The more you test, the more you understand the parsing behaviors of both the DateTime and your own parsing method with a string. – Jamin Dec 12 '17 at 03:32
  • 1
    All of this is actually amazingly perfect. I believe after looking through your code, I might have what I need. As a side note, there is a "date" property to the datetime class. Not sure what format it returns it in, but would be worth looking at. Thanks a TON Jamin. Definitely the answer I was looking for and is easily adaptable to a winform with a few extra handlers. :) – Ryan Wakefield Dec 12 '17 at 03:36