Custom formatting including dates
In my app I present to the user an option to customize the name of the file that gets produced. The format string the program reads is something like "yyyyMMdd-%1-%2-%3-%4"
which the user can customize to his liking.
In this case the format of the date is yyyyMMdd
and the %1
is the trip number like 1000P, %2
is the origin code like PTTTT, %3
is the destination code like PHYUD, and %4
is a secondary stop code like YYYY123开发者_StackOverflow中文版.
I'm having problems taking the actual data and formatting into the custom string. I believe its the date format that I'm getting stuck on. So far I have
sOut = txtFormatPattern.Text
sOut = sOut.Replace("%1", "1000P")
sOut = sOut.Replace("%2", "PTTTT")
sOut = sOut.Replace("%3", "PHYUD")
sOut = sOut.Replace("%4", "YYYY123")
sOut = myDate.ToString(sOut) 'date is July 01, 2007
the output is "20070701-#1000P-PTTTTP12YUD (YYYY123)" The problem obviously here is my last conversion. The string contains key characters that denote a part of the date specifically in PHYUD. So my question is how can I give my user the flexibility to format the output as they wish and then convert that properly?
agp
well i want to replace the tokens with their counterpart as stated above but also include some flexibility for dates and times. I have resolved this by doing the following:
'first replace the tokens by escaping the % character and number so that the
'date/time formatting ignores it
sOut = txtFormatPattern.Text
sOut = sOut.Replace("%1", "\%\1")
sOut = sOut.Replace("%2", "\%\2")
sOut = sOut.Replace("%3", "\%\3")
sOut = sOut.Replace("%4", "\%\4")
'now apply the date/time formatting as set by the user. the end result strips out
'the escape characters and ignores them for date/time formatting
sOut = myDate.ToString(sOut) 'date is July 01, 2007
'we should now have applied the date/time formatting and still have the original
'tokens so just replace
sOut = sOut.Replace("%1", "1000P")
sOut = sOut.Replace("%2", "PTTTT")
sOut = sOut.Replace("%3", "PHYUD")
sOut = sOut.Replace("%4", "YYYY123")
With this routine the user can set the formatting string as "yyyyMMdd-%1-%2-%3-%4" and the resulting output will be "20070701-#1000P-PTTTT-PHYUD-YYYY123"
That should work for any variant of the date/time formatting the user may set in the options since the valid tokens are always denoted by %n.
agp
You can use String.Format
to do what you want. Each section inside curly braces is a placeholder for a parameter you pass to the function.
Optionally, you can put a colon folowed by another formatting string specific to the parameter.
sOut = String.Format("{0:yyyyMMdd} {1} {2} {3} {4}", myDate, "1000P", "PTTTT", "PHYUD", "YYYY123")
精彩评论