Custom Formatting of Strings
page 1 of 2
Published: 01 Dec 2003
Unedited - Community Contributed
Abstract
I recently came across the requirement in our application in which the time was stored as string instead of date data type in the database. The time was stored in the format "hhmm". When it needed to be displayed in the format "hh:mm" then I thought I could use "format" function to format it the way I need. It took me some time to realize that I can not use built-in functions directly on string data type. The solution to the problem is very simple. The following are a few approaches to solution.
by Pani Baruri & Abhijit Mandrekar
Feedback
Average Rating: 
Views (Total / Last 10 Days): 15964/ 46

Custom Formatting of Strings : ToString Implementation

The solution to the problem is very simple. The followings are few approaches to solution.

 

  • Use inline code where required. Use left and right function to separate “hh” and “mm” respectively and then concatenate the strings with “:” character in between.

 

  • Write a common function “FormatHhMmString” that accepts string as input parameter to be formatted. Include the logic as above.

 

  • Write a class that has a shared method “FormatHhMmString” and include the logic from 1st bullet.

 

Imagine that you are storing the date also in simple string format as “mmddyyyy” with no slashes or hyphens in between or phone number as 10 digits with no slashes or hyphens in between. So now you will have to write the 2 functions FormatMmDdYyyyString and FormatTelPhoneString or inline code wherever required.

 

If every developer writes the inline code then there will not be unique approach to come up with the solution. If you write a class then each time there is new user defined format there will be a new method added to the class.

 

ToString Implementation:

To wrap up all we need to do is define a class which implements IFormattable interface and its version of ToString function to custom format the strings. This approach allows developers to use standard ToString function transparently leaving implementation details behind the scene.

 

The ToString function accepts two parameters: the first parameter is a format string (custom format specification) and the second parameter is format provider object. The format provider object usually carries additional information specific to culture, date & time, numbers of targeted users. To keep things simple we will pass Nothing to format provider and apply general (default) formatting to strings when Nothing is passed.

 

The code that implements above scenarios is as follows:

 

Class Code:

Public Class FormatClass

Implements IFormattable

' Assign a value for the class.

Private _myValue As String

' Add a constructor.

Public Sub New(ByVal value As String)

_myValue = value

End Sub

' Write a custom Format method for the type.

Public Overloads Function ToString(ByVal format As String, ByVal fp As IFormatProvider) As String Implements IFormattable.ToString

If format.Equals("hhmm") Then

Return Left(_myValue, 2) & "-" & Right(_myValue, 2)

ElseIf format.Equals("mmddyyyy") Then

Return Left(_myValue, 2) & "-" & Mid(_myValue, 3, 2) & "-" & Right(_myValue, 4)

ElseIf format.Equals("9999999999") Then

Return Left(_myValue, 3) & "-" & Mid(_myValue, 4, 3) & "-" & Right(_myValue, 4)

Else

Return _myValue.ToString(fp)

End If

End Function

End Class

User Interface Code Behind:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim myTime As New FormatClass(TextBox1.Text)

Dim myDate As New FormatClass(TextBox2.Text)

Dim myTelNo As New FormatClass(TextBox3.Text)

Try

lblTimeToString.Text = myTime.ToString("hhmm", Nothing)

lblDateToString.Text = myDate.ToString("mmddyyyy", Nothing)

lbltelToString.Text = myTelNo.ToString("9999999999", Nothing)

Catch ex As Exception

Response.Write(ex.Message)

End Try

End Sub

User Interface (HTML):

<form id="Form1" method="post" runat="server">

<asp:label id="Label3" style="Z-INDEX: 100; LEFT: 386px; POSITION: absolute; TOP: 28px" runat="server" Height="22px" Width="66px">Enter time</asp:label>

<asp:button id="Button2" style="Z-INDEX: 109; LEFT: 495px; POSITION: absolute; TOP: 150px" runat="server" Height="23px" Width="213px" Text="Use ICustomFormatter Interface"></asp:button><asp:textbox id="TextBox1" style="Z-INDEX: 101; LEFT: 471px; POSITION: absolute; TOP: 28px" runat="server" Height="28px" Width="99px"></asp:textbox><br>

<br>

<asp:label id="Label4" style="Z-INDEX: 102; LEFT: 302px; POSITION: absolute; TOP: 69px" runat="server" Height="24px" Width="149px">Enter date (mmddyyyy)</asp:label><asp:textbox id="TextBox2" style="Z-INDEX: 103; LEFT: 471px; POSITION: absolute; TOP: 66px" runat="server" Height="28px" Width="100px"></asp:textbox><br>

<br>

<asp:label id="Label5" style="Z-INDEX: 104; LEFT: 292px; POSITION: absolute; TOP: 109px" runat="server" Height="24px" Width="151px">Enter Tel No (10 digits)</asp:label><asp:textbox id="TextBox3" style="Z-INDEX: 105; LEFT: 471px; POSITION: absolute; TOP: 106px" runat="server" Height="26px" Width="102px"></asp:textbox><br>

<br>

<asp:button id="Button1" style="Z-INDEX: 107; LEFT: 286px; POSITION: absolute; TOP: 150px" runat="server" Height="23px" Width="189px" Text="Use IFormattable Interface"></asp:button>

<asp:table id="Table1" style="Z-INDEX: 108; LEFT: 287px; POSITION: absolute; TOP: 193px" runat="server" Height="58px" Width="460px">

<asp:TableRow>

<asp:TableCell Text="ToString Formatting"></asp:TableCell>

<asp:TableCell Text="String.Format Function"></asp:TableCell>

</asp:TableRow>

<asp:TableRow>

<asp:TableCell>

<asp:label id="lblTimeToString" runat="server" Height="22" Width="189"></asp:label>

</asp:TableCell>

<asp:TableCell>

<asp:label id="lblStringFormat" runat="server" Height="22" Width="189"></asp:label>

</asp:TableCell>

</asp:TableRow>

<asp:TableRow>

<asp:TableCell>

<asp:label id="lblDateToString" runat="server" Height="22" Width="189"></asp:label>

</asp:TableCell>

<asp:TableCell></asp:TableCell>

</asp:TableRow>

<asp:TableRow>

<asp:TableCell>

<asp:label id="lblTelToString" runat="server" Height="22" Width="189"></asp:label>

</asp:TableCell>

<asp:TableCell></asp:TableCell>

</asp:TableRow>

</asp:table></form>

How to work with this example:

Type any 4 digit value in text box (associated label text=Enter time), type 8 digit value in text box (associated label text=Enter date), type 10 digit value in text box (associated label text=Enter Tel. No.) and click button that has a text "Use Iformattable Interface".

Input:

Time: 1234

Date: 02141965

Tel No.: 8562084721

Result:

Time: 12:34 (ToString Method)

Date: 02/14/1965

Tel No.: (856) 208-4721


View Entire Article

User Comments

Title: Just use Microsoft.VisualBasic.Format() Function   
Name: Anthony Missico, Jr.
Date: 2005-11-29 1:57:40 PM
Comment:
Use Microsoft.VisualBasic.Format() Function for simple string transformations.

>? Microsoft.VisualBasic.Format(now, "hhmm")
"1015"

>? Microsoft.VisualBasic.Format(now, "MMddyyyy")
"11292005"

>? Microsoft.VisualBasic.Format(Convert.ToInt64("8886664444"), "(000)000-0000")
"(888)666-4444"


The Format() function also allows the user to specify three sections in the "style" parameter. Each section allows you to format positive, negative, and null values.

>? Microsoft.VisualBasic.Format(1234, "$#,##0.00;($#,##0.00);$-.00")
"$1,234.00"

>? Microsoft.VisualBasic.Format(-4321, "$#,##0.00;($#,##0.00);$-.00")
"($4,321.00)"

>? Microsoft.VisualBasic.Format(0, "$#,##0.00;($#,##0.00);$-.00")
"$-.00"


Since you have to use statements like .ToString("hhmm") why not change it to Format(Control.Text, "hhmm") and be done with it. Save the format interfaces for complex data types. For instance, many years ago I created a StandardizedName class for use in Access Basic. I have since migrated to .NET and renamed the Format() function to ToString(). The function accepts format specifiers of LF (Last, First), LFm (Last, First M.), F (First), L (Last), FL (First Last), FmL (First M. Last), FML (First Middle Last, and so on.


See ".NET Framework Developer's Guide - Customizing Format Strings" for a better discussion, but more importantly it contains the format processing order. For instance, ICustomFormatter is called before IFormattable.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-10-13 1:15:51 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search