[ASP.NET][C#][DateTime]全數字、兩位西元年、AM/PM 字串轉日期

  • 1581
  • 0
  • 2018-04-10

.

例如:要處理的日期字串="03-20-18 04:39PM"

●兩位西元年、AM/PM 字串轉日期:

DateTime dDT = DateTime.ParseExact("03-20-18 04:39PM", "MM-dd-yy hh:mmtt", System.Globalization.CultureInfo.InvariantCulture);

●再把這個日期時間值轉成想要的日期格式:

string sDT = dDT.ToString("yyyy/MM/dd HH:mm");

//結果:"2018/03/20 16:39"

●同理,以下示範連續8位數表示的西元日期字串,轉成強制指定起迄時間為00:00:00~23:59:59的字串如下:

string sStartDate = DateTime.ParseExact("20180315", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-dd 00:00:00");
string sEndDate = DateTime.ParseExact("20180316", "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-dd 23:59:59");

用法例如:

//informix DateTime(From Year to Second)欄位接受傳入的日期格式如下:
//'2018-03-26 00:00:00'
//'2018-03-26 23:59:59'

string SDate = "20180301";
string EDate = "20180331";

string sd = DateTime.ParseExact(SDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-dd 00:00:00");
string ed = DateTime.ParseExact(EDate, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture).ToString("yyyy-MM-dd 23:59:59");

string sql = " Select * from Table1 Where CreateDateTime Between '{0}' and '{1}'; ";
sql = String.Format(sql,sd,ed);