среда, 12 ноября 2008 г.

Format strings - .NET

.NET Format String 101

"I see stuff like {0,-8:G2} passed in as a format string. What exactly does that do?" -- Very Confused String Formatter

The above format can be translated into this:

"{[,][:]}"

argument index: This represent which argument goes into the string.

String.Format("first = {0};second = {1}", "apple", "orange");

String.Format("first = {1};second = {0}", "apple", "orange");

gives the following strings:

"first = apple;second = orange"

"first = orange;second = apple"

alignment (optional): This represent the minimal length of the string.

Postive values, the string argument will be right justified and if the string is not long enough, the string will be padded with spaces on the left.

Negative values, the string argument will be left justied and if the string is not long enough, the string will be padded with spaces on the right.

If this value was not specified, we will default to the length of the string argument.

String.Format("{0,-10}", "apple"); //"apple "

String.Format("{0,10}", "apple"); //" apple"

format string (optional): This represent the format code.

Numeric format specifier is available here. (e.g. C, G...etc.)
Datetime format specifier is available here.

Enumeration format specifier is available here.

Custom Numeric format specifier is available here. (e.g. 0. #...etc.)

Custom formatting is kinda hard to understand. The best way I know how to explain something is via code:

int pos = 10;

int neg = -10;

int bigpos = 123456;

int bigneg = -123456;

int zero = 0;

string strInt = "120ab";

String.Format("{0:00000}", pos); //"00010"

String.Format("{0:00000}", neg); //"-00010"

String.Format("{0:00000}", bigpos); //"123456"

String.Format("{0:00000}", bigneg); //"-123456"

String.Format("{0:00000}", zero); //"00000"

String.Format("{0:00000}", strInt); //"120ab"

String.Format("{0:#####}", pos); //"10"

String.Format("{0:#####}", neg); //"-10"

String.Format("{0:#####}", bigpos); //"123456"

String.Format("{0:#####}", bigneg); //"-123456"

String.Format("{0:#####}", zero); //""

String.Format("{0:#####}", strInt); //"120ab"

While playing around with this, I made an interesting observation:

String.Format("{0:X00000}", pos); //"A"

String.Format("{0:X00000}", neg); //"FFFFFFF6"

String.Format("{0:X#####}", pos); //"X10"

String.Format("{0:X#####}", neg); //"-X10"

The "0" specifier works well with other numeric specifier, but the "#" doesn't. Umm... I think the "Custom Numeric Format String" probably deserve a whole post of it's own. Since this is only the "101" post, I'll move on to the next argument in the format string.

zeros (optional): It actually has a different meaning depending on which numeric specifier you use.

int neg = -10;

int pos = 10;

// C or c (Currency): It represent how many decimal place of zeros to show.

String.Format("{0:C4}", pos); //"$10.0000"

String.Format("{0:C4}", neg); //"($10.0000)"

// D or d (Decimal): It represent leading zeros

String.Format("{0:D4}", pos); //"0010"

String.Format("{0:D4}", neg); //"-0010"

// E or e (Exponential): It represent how many decimal places of zeros to show.

String.Format("{0:E4}", pos); //"1.0000E+001"

String.Format("{0:E4}", neg); //"-1.0000E+001"

// F or f (Fixed-point): It represent how many decimal places of zeros to show.

String.Format("{0:F4}", pos); //"10.0000"

String.Format("{0:F4}", neg); //"-10.0000"

// G or g (General): This does nothing

String.Format("{0:G4}", pos); //"10"

String.Format("{0:G4}", neg); //"-10"

// N or n (Number): It represent how many decimal places of zeros to show.

String.Format("{0:N4}", pos); //"10.0000"

String.Format("{0:N4}", neg); //"-10.0000"

// P or p (Percent): It represent how many decimal places of zeros to show.

String.Format("{0:P4}", pos); //"1,000.0000%"

String.Format("{0:P4}", neg); //"-1,000.0000%"

// R or r (Round-Trip): This is invalid, FormatException is thrown.

String.Format("{0:R4}", pos); //FormatException thrown

String.Format("{0:R4}", neg); //FormatException thrown

// X or x (Hex): It represent leading zeros

String.Format("{0:X4}", pos); //"000A"

String.Format("{0:X4}", neg); //"FFFFFFF6"

// nothing: This is invalid, no exception is thrown.

String.Format("{0:4}", pos)); //"4"

String.Format("{0:4}", neg)); //"-4"

In summary, there are four types of behaviour when using this specifier:

Leading Zeros: D, X

Trailing Zeros: C, E, F, N, P

Nothing: G

Invalid: R,

Now, that we've gone through the valid specifiers, you can actually use this in more than just String.Format(). For example, when using this with Byte.ToString():

Byte b = 10;

b.ToString("D4"); //"0010"

b.ToString("X4"); //"000A"



DateTime.ToString, Format


DateTime.ToString() Patterns

All the patterns:

0 MM/dd/yyyy 08/22/2006
1 dddd, dd MMMM yyyy Tuesday, 22 August 2006
2 dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
3 dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
4 dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
5 dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
6 dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
7 MM/dd/yyyy HH:mm 08/22/2006 06:30
8 MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
9 MM/dd/yyyy H:mm 08/22/2006 6:30
10 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
10 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
10 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
11 MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07
12 MMMM dd August 22
13 MMMM dd August 22
14 yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
15 yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
16 ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT
17 ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT
18 yyyy'-'MM'-'dd'T'HH':'mm':'ss 2006-08-22T06:30:07
19 HH:mm 06:30
20 hh:mm tt 06:30 AM
21 H:mm 6:30
22 h:mm tt 6:30 AM
23 HH:mm:ss 06:30:07
24 yyyy'-'MM'-'dd HH':'mm':'ss'Z' 2006-08-22 06:30:07Z
25 dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
26 yyyy MMMM 2006 August
27 yyyy MMMM 2006 August

The patterns for DateTime.ToString ( 'd' ) :

0 MM/dd/yyyy 08/22/2006

The patterns for DateTime.ToString ( 'D' ) :

0 dddd, dd MMMM yyyy Tuesday, 22 August 2006

The patterns for DateTime.ToString ( 'f' ) :

0 dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
1 dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
2 dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
3 dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM

The patterns for DateTime.ToString ( 'F' ) :

0 dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07

The patterns for DateTime.ToString ( 'g' ) :

0 MM/dd/yyyy HH:mm 08/22/2006 06:30
1 MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
2 MM/dd/yyyy H:mm 08/22/2006 6:30
3 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM

The patterns for DateTime.ToString ( 'G' ) :

0 MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07

The patterns for DateTime.ToString ( 'm' ) :

0 MMMM dd August 22

The patterns for DateTime.ToString ( 'r' ) :

0 ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT

The patterns for DateTime.ToString ( 's' ) :

0 yyyy'-'MM'-'dd'T'HH':'mm':'ss 2006-08-22T06:30:07

The patterns for DateTime.ToString ( 'u' ) :

0 yyyy'-'MM'-'dd HH':'mm':'ss'Z' 2006-08-22 06:30:07Z

The patterns for DateTime.ToString ( 'U' ) :

0 dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07

The patterns for DateTime.ToString ( 'y' ) :

0 yyyy MMMM 2006 August

Building a custom DateTime.ToString Patterns

The following details the meaning of each pattern character. Not the K and z character.

d Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero
dd Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero
ddd Represents the abbreviated name of the day of the week (Mon, Tues, Wed etc)
dddd Represents the full name of the day of the week (Monday, Tuesday etc)
h 12-hour clock hour (e.g. 7)
hh 12-hour clock, with a leading 0 (e.g. 07)
H 24-hour clock hour (e.g. 19)
HH 24-hour clock hour, with a leading 0 (e.g. 19)
m Minutes
mm Minutes with a leading zero
M Month number
MM Month number with leading zero
MMM Abbreviated Month Name (e.g. Dec)
MMMM Full month name (e.g. December)
s Seconds
ss Seconds with leading zero
t Abbreviated AM / PM (e.g. A or P)
tt AM / PM (e.g. AM or PM
y Year, no leading zero (e.g. 2001 would be 1)
yy Year, leadin zero (e.g. 2001 would be 01)
yyy Year, (e.g. 2001 would be 2001)
yyyy Year, (e.g. 2001 would be 2001)
K Represents the time zone information of a date and time value (e.g. +05:00)
z With DateTime values, represents the signed offset of the local operating system's time zone from Coordinated Universal Time (UTC), measured in hours. (e.g. +6)
zz As z but with leadin zero (e.g. +06)
zzz With DateTime values, represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. (e.g. +06:00)
f Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value.
ff Represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value.
fff Represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.
ffff Represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. While it is possible to display the ten thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
fffff Represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value. While it is possible to display the hundred thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
ffffff Represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a second in a date and time value. While it is possible to display the millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
fffffff Represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value. While it is possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's resolution is approximately 10-15 milliseconds.
F Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. Nothing is displayed if the digit is zero.
: Represents the time separator defined in the current DateTimeFormatInfo..::.TimeSeparator property. This separator is used to differentiate hours, minutes, and seconds.
/ Represents the date separator defined in the current DateTimeFormatInfo..::.DateSeparator property. This separator is used to differentiate years, months, and days.
" Represents a quoted string (quotation mark). Displays the literal value of any string between two quotation marks ("). Your application should precede each quotation mark with an escape character (\).
' Represents a quoted string (apostrophe). Displays the literal value of any string between two apostrophe (') characters.
%c Represents the result associated with a c custom format specifier, when the custom date and time format string consists solely of that custom format specifier. That is, to use the d, f, F, h, m, s, t, y, z, H, or M custom format specifier by itself, the application should specify %d, %f, %F, %h, %m, %s, %t, %y, %z, %H, or %M. For more information about using a single format specifier, see Using Single Custom Format Specifiers.


References

http://blogs.msdn.com/kathykam/archive/2006/03/29/net-format-string-101-C_2300_-strings.aspx


http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

Комментариев нет: