Maybe it’s a n00b question but I’ve looked at the .net/C# MSDN Library and on this site and have yet to come to a clear answer… say I had For Ex:
(this is not exactly the problem, as I’m not creating the string but reading them out of a DB. But serves to illustrate what I’m working with…)
string dob = "01/02/1990";
dob.ToString("MM/dd/YY"); //however, I can't do this. compiler gives me an error...
likely because it is already a string? How then could I get the string into the format that I want using specifiers, when it’s already a string?
I know I could convert it to something else (a DateTime for Ex) and convert back to string using the ToString()…but this seems counter productive… to me at least
I also have several other “kinds” of string variables I’m trying to display into specific formats whilst saving them to a Idictionary for printing into a pdf’s fields.
For ex:
d["amount"] = prod.sales.StringAmount; //(here StringSmount holds say 50000 (gotten from a DB), which I want to display as "50,000")
However, I also can’t do prod.sales.StringAmount.ToString(“N”, CultureInfo.CurrentUICulture); cuz it’s already a string! Is there an easy way to do this
or need I mess with String Buffers or the StringBuilder class??
thanks!
You can do something like this:
and then
will work.
Note that
DateTime.Parse()has various options for the possible date-time formats to accept, and that there is also aTryParse()version that returnsfalseif the string is not a valid date – instead than throwing an exception. There are alsoDateTime.ParseExact()andDateTime.TryParseExact()variations.Use the same approach for other data types beside date-times: first convert the input string in the correct data type (integer, float etc) – using the various
Parse()orTryParse()methods, and then format the result of this conversion.