關於DateTime的自定義轉換
阿新 • • 發佈:2017-08-30
一個 val clas 實現 mon omd tryparse try and
關於DateTime的自定義轉換。把字符串時間轉換成可以供DateTime類型識別的字符串類型的粗略實現。
/// <summary> /// 把從數據庫中讀取的字符串的CurrentTime數據轉換成可以被DateTime類型識別的格式 /// 可識別的格式如: 2009-06-15T13:45:30.6175425 -> 6175425 /// </summary> public class CustomDateTimeConverter { public CustomDateTimeConverter() { }View Code//實現在時分秒間插入“:” public string TimeStringConverter(string s) { string s2 = InsertChar(s, 3, ‘:‘); string s3 = InsertChar(s2, 1, ‘:‘); return s3; } //在第m+1個位置後插入一個字符c // if s.length < m, insert into the end ????? public stringInsertChar(string s, int m, char c) { if (s.Length <= m) return s + c; else return s.Insert(m + 1, new string(c, 1)); //int length = s.Length; //length = length + 1; //char[] temp = new char[length]; //for (int i = length - 1; i > m; i--)//{ // temp[i] = s.ToArray()[i - 1]; //} //temp[m + 1] = c; //for (int i = 0; i <= m; i++) //{ // temp[i] = s.ToArray()[i]; //} //s = new string(temp); //return s; } public string DateStringConverter(string s) { string s1= InsertChar(s, 5, ‘-‘); string s2 = InsertChar(s1, 3, ‘-‘); return s2; } /* Get sub string. */ private static string subString(string s, int index, int len) { if (s.Length <= index) return string.Empty; else if (s.Length <= (index + len)) return s.Substring(index); else return s.Substring(index, len); } /* Parse a string into the int value with min and max. */ private static int toInt(string s, int min, int max) { int tmp; int.TryParse(s, out tmp); if (tmp < min) tmp = min; else if (tmp > max) tmp = max; return tmp; } /* Try to parse date(YYYYMMDD) and time(HHMMSS.MMM) into DateTime. * * return default value if input a invalid parameter. * */ public static DateTime TryToDateTime(string date, string time) { DateTime min = DateTime.MinValue; DateTime max = DateTime.MaxValue; // year int index = 0; int year = toInt(subString(date, index, 4), min.Year, max.Year); // month index += 4; int month = toInt(subString(date, index, 2), min.Month, max.Month); // day index += 2; int day = toInt(subString(date, index, 2), min.Day, max.Day); // hour index = 0; int hour = toInt(subString(time, index, 2), min.Hour, max.Hour); // minute index += 2; int minute = toInt(subString(time, index, 2), min.Minute, max.Minute); // second index += 2; int second = toInt(subString(time, index, 2), min.Second, max.Second); // millisecond index += 3; int millisecond = toInt(subString(time, index, 3), min.Millisecond, max.Millisecond); return new DateTime(year, month, day, hour, minute, second, millisecond); } }
關於DateTime的自定義轉換