WPFNewbie Wannabe
WPFNewbie Wannabe

Reputation: 198

How can I format string values using a mask in a generic way?

Background: We have a system that receives data from another backend system. We handle the displaying of that data, and we have our own XML templates to control how certain things are displayed (i.e. we have our own column templates to dictate what the column headers are, etc.) One thing we would like to support is the ability to provide a mask for these column templates that would apply to the values coming from the backend. Below is a scenario that I'm having trouble with.

Problem: I can't seem to get a simple string format working. I'd like to format a STRING value of four digits (i.e. "1444") in a time format (i.e. "14:44"). I've tried:

String.Format("{0:00:00}", "1444")

Note the importance of the input being a STRING. If I supply an int value, the format will work. The reason I cannot use this is because all the data we receive from the backend is in string format, and we'd like for this to be generic (so casting isn't really an option).

By generic, I mean I'd like to specify a mask in our own XML templates, something like:

<MyColumnTemplate Id="MyColumn" Mask="00:00" />

and to use that mask in a string format call for string values? If the mask fails, we could just simply return the original value (as the String.Format() method already does by default).

Edit: To help clarify, here is a simplified version of what I'd like to be able to do in code:

string inputValue = "1444";
string maskValueFromXml = "00:00";

string mask = "{0:" + maskValueFromXml + "}";
string myDesiredEndResult = String.Format(mask, inputValue);

Upvotes: 1

Views: 13633

Answers (2)

terrybozzio
terrybozzio

Reputation: 4542

The thing is you are working string to string,since you ask for time and phone number they are all numbers then try this trick(if we can call it that :)):

string result = string.Format("{0:00:00}", int.Parse("1444"));

For phone number:

string result = string.Format("{0:000-000-0000}", int.Parse("1234560789"));

You can even place your desired masks in a dictionary for example and do this:

Dictionary<string, string> masks = new Dictionary<string, string>();
masks.Add("Phone", "{0:000-000-0000}");
masks.Add("Time", "{0:00:00}");
string test = "1234560789";
string result = string.Format(masks["Phone"], int.Parse(test));

Upvotes: 1

Andras Sebo
Andras Sebo

Reputation: 1140

Try with DateTime.TryParseExact, e.g:

    DateTime dateEntered;
    string input = "1444";

    if (DateTime.TryParseExact(input, "HH:mm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateEntered))
    {
        MessageBox.Show(dateEntered.ToString());
    }
    else
    {
        MessageBox.Show("You need to enter valid 24hr time");
    }

After that, you can use string.Format, predefined formats on MSDN.

Upvotes: 0

Related Questions