Dynamically formatting a string at runtime

I have an application that displays data based on values in a table, so for instance I may have a date field in a particular table that needs to be formatted in a certain way (YYYY-MM-DD, etc).  I have all the layouts and formats in a table but I need to be able to dynamically apply them at run time.  So here's an example:

The data that I'm trying to display is 08/04/09 but I need to format it as the user sees fit, so it could be 2009-08-04, or 04-08-2009, or 04-08-09, etc.  I have the code I need to do the formatting but cannot figure out how to apply it at runtime.

I've searched online and have only found how to apply a format to currency, numbers, date time.  Nothing on how to manipulate a string using String.Format().

This is just an example of one particular field, the formatting can occur on any field at any time and it could be any format.  So currency, or date time, number, left(), right(), etc...)  So i need to be able to apply any of those formats at runtime.

I've attached a code snippet below so you can get an idea of what I'm trying to do.

I know the syntax is VB.Net, but a C# response would be fine as well.
Thanks in advance.

' Original value.
Dim tmp As String = "08/14/09"

' New formatted value.
Dim tmp1 As String
' This data would be retreived out of a database table.
' Trying to format the data as YYYY-MM-DD
Dim fmt As String = """20"" & tmp_input.Substring(7,2) & ""-"" & tmp_input.Substring(1,2) & ""-"" & tmp_input.Substring(4,2)"

' Save the results of the original data with the format applied.
tmp1 = String.Format(fmt, tmp)

Open in new window

Who is Participating?
Miguel OzSoftware EngineerCommented:
This C# code will do:
String.Format("20{0}-{1}-{2}",tmp_input.Substring(7,2),tmp_input.Substring(1,2) , tmp_input.Substring(4,2) ) ;

why are you not using this in your query---

select convert(varchar(20), getdate() , 102) as currentdate
this return u YYYY/MM/DD format.


select convert(varchar(20), getdate() , 104) as currentdate
this return u DD/MM/YYYY format.


an if you want to change date after retrive data then
manage this as par requirement
String.Format("20{0}-{1}-{2}",tmp_input.Substring(7,2),tmp_input.Substring(1,2) , tmp_input.Substring(4,2)  

above is return YYYY/MM/DD formet you can manage this also.
chuck620Author Commented:
apexpert, the data is not coming from a database, it's coming from a file so that's why I need to do it in code.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.