方法1:
我們在處理入日期格式式常用DateTime.Pares() 但是這個形式的轉換是相當有限的,有些C#是會不懂你寫入的日期格式的如20031231大家都明白是2003-12-31號可以C#不認識他.我們可以這樣子進行如下 //設置語言國家 System.IFormatProvider format=new System.Globalization.CultureInfo("zh-CN",true); //指定轉換格式 Response.Write(DateTime.ParseExact(this.TextBox1.Text,"yyyyMMdd",format)); 這樣他就能看出20031231號的日期格式了 不過可惜他只能夠對yyyyMMdd形式進行不能對其它格式進行轉換是不是美中不足? 不過.NET提供了另一種重載版本. public static DateTime ParseExact(string, string[], IFormatProvider, DateTimeStyles); 可對指定的幾種日期格式進行轉換.
示例: string strDateFormat = "yyyyMMdd";string date="20061141"; DateTime.ParseExact(date, strDateFormat, new CultureInfo("zh-CN"), DateTimeStyles.AllowWhiteSpaces); 不過具體的操作我想還是大家自己去試驗一下效果可能會更好一些。
方法2:
日期必須是固定位數,20051126是8位,20050203就不能這么表示成200523 //分別獲取20051126中的年、月、日字符串 string yyyy="20051126".Substring(0,4); string mm="20051126".Substring(4,2); string dd="20051126".Substring(5,2); //拼寫符合日期格式的字符串 string riqi=yyyy+"-"+mm+"-"+dd; //將符合日期格式的字符串轉化為DateTime數據類型 DateTime dt=Convert.ToDateTime(riqi);
也可以用
string s="20051126"; s =s.Insert(4,"/"); s=s.Insert(6,"/");
把20051126變為2005/11/26