对C#DateTime日期类型格式化显示的总结
时间:2011-04-07 来源:西路
C#(ASP.NET)DateTime日期类型格式化显示 (转载)
转载:http://blog.csdn.net/codetian/archive/2007/07/26/1710157.aspx
方便自己查找所以记录下来。
1.绑定时格式化日期方法:
<ASP:BOUNDCOLUMN DATAFIELD= "JoinTime " DATAFORMATSTRING= "{0:yyyy-MM-dd} " >
<ITEMSTYLE WIDTH= "18% " > </ITEMSTYLE >
</ASP:BOUNDCOLUMN >
2.数据控件如DataGrid/DataList等的件格式化日期方法:
e.Item.Cell[0].Text = Convert.ToDateTime(e.Item.Cell[0].Text).ToShortDateString();
3.用String类转换日期显示格式:
String.Format( "yyyy-MM-dd ",yourDateTime);
4.用Convert方法转换日期显示格式:
Convert.ToDateTime("2005-8-23").ToString
("yyMMdd",System.Globalization.DateTimeFormatInfo.InvariantInfo); //支持繁体数据库
5.直接用ToString方法转换日期显示格式:
DateTime.Now.ToString("yyyyMMddhhmmss");
DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss")
6.只显示年月
DataBinder.Eval(Container.DataItem,"starttime","{0:yyyy-M}")
7.显示时间所有部分,包括:年月日时分秒
<asp:BoundColumn DataField="收款时间" HeaderText="收款时间"
DataFormatString="{0:yyyy-MM-dd HH24:mm:ss}">
</asp:BoundColumn>
8.格式化从数据库中读取的时间
Convert.ToDateTime(dr["MT_ENDate"]).ToShortDateString();Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1710157
using System;using System.Globalization;
public class MainClass {
public static void Main(string[] args) {
DateTime dt = DateTime.Now;
String[] format = {
"d", "D",
"f", "F",
"g", "G",
"m",
"r",
"s",
"t", "T",
"u", "U",
"y",
"dddd, MMMM dd yyyy",
"ddd, MMM d \"'\"yy",
"dddd, MMMM dd",
"M/yy",
"dd-MM-yy",
};
String date;
for (int i = 0; i < format.Length; i++) {
date = dt.ToString(format[i], DateTimeFormatInfo.InvariantInfo);
Console.WriteLine(String.Concat(format[i], " :" , date));
}
/** Output.
*
* d :08/17/2000
* D :Thursday, August 17, 2000
* f :Thursday, August 17, 2000 16:32
* F :Thursday, August 17, 2000 16:32:32
* g :08/17/2000 16:32
* G :08/17/2000 16:32:32
* m :August 17
* r :Thu, 17 Aug 2000 23:32:32 GMT
* s :2000-08-17T16:32:32
* t :16:32
* T :16:32:32
* u :2000-08-17 23:32:32Z
* U :Thursday, August 17, 2000 23:32:32
* y :August, 2000
* dddd, MMMM dd yyyy :Thursday, August 17 2000
* ddd, MMM d "'"yy :Thu, Aug 17 '00
* dddd, MMMM dd :Thursday, August 17
* M/yy :8/00
* dd-MM-yy :17-08-00
*/
}
}