日期和时间的转换

80酷酷网    80kuku.com

  转换The DateTime data type also contains a Format method and a ToString method that return a string-formatted representation of the original value. The Format method can be used to format a value in one of fifteen common ways, while the ToString method can only be used to format a value in one way.

The Format method takes the following form, where XXX is the name of the numeric base data-type:

virtual XXX Format(String* format,IServiceObjectProvider* sp)
Similar to the Format methods found in other .NET Framework data types, the DateTime Format method takes a string format character and an IServiceObjectProvider object. The IServiceObjectProvider object specifies the culture. The method defaults to the current culture if null (in Visual Basic Nothing) is passed.

The following table shows the valid format strings.


Format character Description Default return format
d Short date pattern MM/dd/yyyy
D Long date pattern dddd, MMMM dd, yyyy
f Full (long date + short time) dddd, MMMM dd, yyyy HH:mm
F Full date time pattern (long date + long time) dddd, MMMM dd, yyyy HH:mm:ss
g General (short date + short time) MM/dd/yyyy HH:mm
G General (short date + long time) MM/dd/yyyy HH:mm:ss
m,M Month day pattern MMMM dd
r,R RFC1123 pattern  ddd, dd MMM yyyy HH':'mm':'ss'GMT'
s Sortable date time pattern: conforms to ISO 8601 yyyy-MM-dd HH:mm:ss
t Short time pattern HH:mm
T Long time pattern HH:mm:ss
u Similar to "s"but uses universal time instead of local time. yyyy-MM-dd HH:mm:ss
U Universal sortable date time pattern dddd, MMMM dd, yyyy HH:mm:ss
Y,y Year month pattern MMMM, yyyy


Given a DateTime object, MyDate, representing 12:01 AM Sunday, January 1, 2000, the following example illustrates some of the formatting options available:

[C#]
MyDate.Format( "d", null );
// returns the string "01/01/2000"

MyDate.Format( "D", null );
// returns the string "Sunday, January 1, 2000"

MyDate.Format( "f", null );
// returns the string "Sunday January 1, 2000 12:01 AM"
The ToString Method will quickly convert a DateTime type value into a string. Similar to other .NET Framework base types, it requires no arguments and is easy to use. Unlike the Format method, the ToString method is unaffected by the current culture and only takes one form. The following example converts a DateTime value into a string value:

[C#]

DateTime MyDate = new DateTime(2000, 01, 01)
MyDate.ToString();
//returns "01/01/2000 00:00:00"


分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: