http://www.aygfsteel.com/ebecket 返還網
          隨筆-140  評論-11  文章-131  trackbacks-0

          C# Use DateTime.ParseExact() instead of DateTime.Parse()

          I didn’t notice this until today, the DateTime I retrieve from my database has the format of yyyy/MM/dd hh:mm:ss.fff

          and if I use DateTime.Parse(), the .fff value will be lost.

          After searching google, I find out that not only DateTime.Parse() has this one problem, it also has problem with culture setting.

          So, whenever you what to parse a DateTime, use DateTime.ParseExact().

          Here is an useful example :

          string[] DateTimeList = {
          "yyyy/M/d tt hh:mm:ss",
          "yyyy/MM/dd tt hh:mm:ss",
          "yyyy/MM/dd HH:mm:ss",
          "yyyy/M/d HH:mm:ss",
          "yyyy/M/d",
          "yyyy/MM/dd"
          }; 
          DateTime dt = DateTime.ParseExact(" 2008/  3/18   PM 02: 50:23  ",
          DateTimeList,CultureInfo.InvariantCulture,
          DateTimeStyles.AllowWhiteSpaces
          );

          Remember, CultureInfo is important to parsing, for example tt in Chinese will be 上午/下午, in en-US will be AM/PM. You can use CultureInfo.CreateSpecificCulture() to create the culture you need.
          A small pattern reference

          yyyy year ‘2009′
          MM month ‘04′
          dd day ‘17′
          HH 24 hour ‘23′
          hh 12 hour ‘11′
          mm minutes ‘59′
          ss seconds ‘30′
          tt AM/PM
          zzz GMT
          posted on 2009-11-20 17:00 becket_zheng 閱讀(1860) 評論(0)  編輯  收藏 所屬分類: C#
          主站蜘蛛池模板: 河曲县| 平远县| 拉萨市| 江西省| 尤溪县| 延寿县| 邓州市| 临安市| 特克斯县| 涟源市| 那曲县| 陇川县| 赤峰市| 阜新市| 清新县| 体育| 牙克石市| 阿克| 丹东市| 镶黄旗| 岳普湖县| 托里县| 隆昌县| 襄城县| 油尖旺区| 瑞丽市| 瑞安市| 舟曲县| 保山市| 建平县| 盐亭县| 龙江县| 苍溪县| 翁牛特旗| 肇庆市| 陆良县| 黔南| 石家庄市| 阳朔县| 嘉禾县| 佛冈县|