1. 程式人生 > >mysql——時間欄位型別與C#中datetime

mysql——時間欄位型別與C#中datetime

一、引言

做專案的時候開始糾結於用2013-01-01 12-12-12儲存還是用 2013-01-01儲存,這個設計到的問題是mysql中時間欄位的選擇問題:date、time或者datetime;

第二個糾結的地方是C#中是否有資料型別與之一一對應,答案是否定的,就一個datetime,這個datetime可以容納大部分時間型別資料;

最重要的大家記住,反正mysql中時間欄位最終也是字串,就是有規則的字串。

主要轉換流程跟字串的區別就是多了C#中的datatime:


正向傳遞這樣

string time=Convert.ToDateTime(dt.Rows[i]["F_START_TIME"]).ToString("yyyy.MM.dd");
逆向傳遞類似,就是先將字串轉換為datatime型別,然後寫入sql插入資料庫。

二、mysql中的時間欄位型別

mysql有5種表示時間值的日期和時間型別,分別為、DATE,TIME,YEAR,DATETIME,TIMESTAMP。

TIMESTAMP型別有專有的自動更新特性,

TIMESTAMP型別有專有的自動更新特性,

TIMESTAMP型別有專有的自動更新特性,

型別 大小
(位元組)
範圍 格式 用途
DATE 3 1000-01-01/9999-12-31 YYYY-MM-DD 日期值
TIME 3 '-838:59:59'/'838:59:59' HH:MM:SS
時間值或持續時間
YEAR 1 1901/2155 YYYY 年份值
DATETIME 8 1000-01-01 00:00:00/9999-12-31 23:59:59 YYYY-MM-DD HH:MM:SS 混合日期和時間值
TIMESTAMP 4 1970-01-01 00:00:00/2037 年某時 YYYYMMDD HHMMSS 混合日期和時間值,時間戳

三、C#中datetime操作

獲得當前系統時間: DateTime dt = DateTime.Now;
Environment.TickCount可以得到“系統啟動到現在”的毫秒值
DateTime now = DateTime.Now;
Console.WriteLine(now.ToString("

yyyy-MM-dd"));  //按yyyy-MM-dd格式輸出sConsole.WriteLine(dt.ToString());    //  26/11/2009 AM 11:21:30Console.WriteLine(dt.ToFileTime().ToString());   //   129036792908014024
// Converts the value of the current System.DateTime object to a Windows file timeConsole.WriteLine(dt.ToFileTimeUtc().ToString());  //     129036792908014024
// Converts the value of the current System.DateTime object to a Windows file timeConsole.WriteLine(dt.ToLocalTime().ToString());   //       26/11/2009 AM 11:21:30
// Converts the value of the current System.DateTime object to local time.Console.WriteLine(dt.ToLongDateString().ToString());   //      2009年11月26日Console.WriteLine(dt.ToLongTimeString().ToString());  //      AM 11:21:30Console.WriteLine(dt.ToOADate().ToString());   //      40143.4732731597Console.WriteLine(dt.ToShortDateString().ToString());   //     26/11/2009Console.WriteLine(dt.ToShortTimeString().ToString());   //     AM 11:21Console.WriteLine(dt.ToUniversalTime().ToString());   //       26/11/2009 AM 3:21:30Console.WriteLine(dt.Year.ToString());   //        2009Console.WriteLine(dt.Date.ToString());   //        26/11/2009 AM 12:00:00Console.WriteLine(dt.DayOfWeek.ToString());  //       ThursdayConsole.WriteLine(dt.DayOfYear.ToString());   //       330Console.WriteLine(dt.Hour.ToString());       //        11Console.WriteLine(dt.Millisecond.ToString());   //     801        (毫秒)Console.WriteLine(dt.Minute.ToString());   //      21Console.WriteLine(dt.Month.ToString());   //       11Console.WriteLine(dt.Second.ToString());   //      30Console.WriteLine(dt.Ticks.ToString());   //       633948312908014024
Console.WriteLine(dt.TimeOfDay.ToString());   //       12:29:51.5181524

四、總結

  • 資料庫與C#中時間型別選擇;
  • 時間資料傳遞流程;
  • mysql中的時間欄位型別;
  • C#中datetime的操作;