关于DateTime的自定义转换
Posted 积跬步---行千里
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于DateTime的自定义转换相关的知识,希望对你有一定的参考价值。
关于DateTime的自定义转换。把字符串时间转换成可以供DateTime类型识别的字符串类型的粗略实现。
/// <summary> /// 把从数据库中读取的字符串的CurrentTime数据转换成可以被DateTime类型识别的格式 /// 可识别的格式如: 2009-06-15T13:45:30.6175425 -> 6175425 /// </summary> public class CustomDateTimeConverter { public CustomDateTimeConverter() { } //实现在时分秒间插入“:” 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 string InsertChar(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的自定义转换的主要内容,如果未能解决你的问题,请参考以下文章