| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680 |
- /*******************************************************************************
- * Copyright(c) 2012 dongke All rights reserved. / Confidential
- * 类的信息:
- * 1.程序名称:DateTimeManager.cs
- * 2.功能描述:提供跟DateTime相关的功能,例如:字符转日期,日期转字符等
- * 编辑履历:
- * 作者 日期 版本 修改内容
- * 欧阳涛 2012/06/07 1.00 新建
- *******************************************************************************/
- using System;
- using System.Text.RegularExpressions;
- namespace Dongke.IBOSS.PRD.Basics.Library
- {
- /// <summary>
- /// 提供跟DateTime相关的功能,例如:字符转日期,日期转字符等
- /// </summary>
- public class DateTimeManager
- {
- #region 常量定义
- /// <summary>
- /// 日期格式的字符串格式数组<br/>
- /// <br/>
- /// 格式<br/>
- /// ・YYYY:年(公历、4位数字)<br/>
- /// ・YY :年(公历、4位数字)<br/>
- /// ・MMM:月(JAN/FEB/MAR/APR/MAY/JUN/JUL/AUG/SEP/OCT/NOV/DEC)<br/>
- /// ・MM :月(2位数字)<br/>
- /// ・M :月(可变位数数字)<br/>
- /// ・DD:日(2位数字)<br/>
- /// ・D :日(可变位数数字)<br/>
- /// <br/>
- /// ・[ ] :空字符串<br/>
- /// ・[/] :区分字符串(分隔符)<br/>
- /// </summary>
- private static string[] FORMAT_LIST_FOR_DATE = new string[]
- {
- "YYYY_/_MM_/_DD",
- "YYYY_/_MM_/_D",
- "YYYY_/_M_/_DD",
- "YYYY_/_M_/_D",
- "YY_/_MM_/_DD",
- "YY_/_MM_/_D",
- "YY_/_M_/_DD",
- "YY_/_M_/_D",
- "MM_/_DD",
- "MM_/_D",
- "M_/_DD",
- "M_/_D",
- "YYYY_MM_DD",
- "YY_MM_DD",
- "MM_DD",
- "DD_/_MMM_/_YYYY",
- "DD_/_MMM_/_YY",
- "DD_/_MMM",
- "DD_MMM_YYYY",
- "DD_MMM_YY",
- "DD_MMM",
- "YYYY_/_MM"
- };
- /// <summary>
- /// 时间格式的字符串格式数组<br/>
- /// <br/>
- /// 格式<br/>
- /// ・hh :小时(2位数字)<br/>
- /// ・h :小时(可变位数数字)<br/>
- /// ・mm :分钟(2位数字)<br/>
- /// ・m :分钟(可变位数数字)<br/>
- /// ・ss :秒(2位数字)<br/>
- /// ・s :秒(可变位数数字)<br/>
- /// <br/>
- /// ・[ ] :空字符串<br/>
- /// ・[/] :区分字符串(分隔符)<br/>
- /// </summary>
- private static string[] FORMAT_LIST_FOR_TIME = new string[]
- {
- "hh_mm",
- "h_mm",
- "hh_/_mm",
- "hh_/_m",
- "h_/_mm",
- "h_/_m",
- "hh_/_mm_/_ss",
- "hh_/_mm_/_s",
- "hh_/_m_/_ss",
- "hh_/_m_/_s",
- "h_/_mm_/_ss",
- "h_/_mm_/_s",
- "h_/_m_/_ss",
- "h_/_m_/_s"
- };
- /// <summary>
- /// 日期和时间的字符串数组
- /// </summary>
- private static string[][] FORMAT_LIST = new string[][]
- {
- FORMAT_LIST_FOR_DATE,
- FORMAT_LIST_FOR_TIME
- };
- /// <summary>
- /// 英文月的数组
- /// </summary>
- private static string[] EMONTH_LIST = new string[]
- {
- "January",
- "Febuary",
- "March",
- "April",
- "May",
- "June",
- "July",
- "August",
- "September",
- "October",
- "November",
- "December",
- };
- /// <summary>
- /// 英文星期数组
- /// </summary>
- private static string[] EWDAY_LIST = new string[]
- {
- "Sunday",
- "Monday",
- "Tuesday",
- "Wednesday",
- "Thursday",
- "Friday",
- "Saturday",
- };
- /// <summary>
- /// 中文星期数组
- /// </summary>
- private static string[] CWDAY_LIST = new string[]
- {
- "星期一",
- "星期二",
- "星期三",
- "星期四",
- "星期五",
- "星期六",
- "星期日",
- };
- #endregion
- #region 枚举
- /// <summary>
- /// 日期的种类
- /// </summary>
- private enum DateItemType
- {
- /// <summary>
- /// 年
- /// </summary>
- Year,
- /// <summary>
- /// 月
- /// </summary>
- Month,
- /// <summary>
- /// 日
- /// </summary>
- Day,
- /// <summary>
- /// 星期
- /// </summary>
- DayOfWeek,
- /// <summary>
- /// 小时
- /// </summary>
- Hour,
- /// <summary>
- /// 分钟
- /// </summary>
- Minute,
- /// <summary>
- /// 秒
- /// </summary>
- Second,
- /// <summary>
- /// 毫秒
- /// </summary>
- Millisecond
- }
- #endregion
- #region 公开方法/函数
- #region DateTime
- /// <summary>
- /// 取得当月第一天
- /// </summary>
- /// <param name="date"></param>
- /// <returns></returns>
- public static DateTime GetFirstDateInMonth(DateTime date)
- {
- return date.AddDays(1 - date.Day);
- }
- /// <summary>
- /// 取得该月的最后一天
- /// </summary>
- /// <param name="date"></param>
- /// <returns></returns>
- public static DateTime GetLastDateInMonth(DateTime date)
- {
- DateTime firstDate = GetFirstDateInMonth(date);
- return firstDate.AddMonths(1).AddDays(-1);
- }
- /// <summary>
- /// 取得本周的第一天的日期
- /// </summary>
- /// <param name="date">日期</param>
- /// <param name="firstDayOfWeek">星期的第一天是星期几,周一或者周日</param>
- /// <returns></returns>
- public static DateTime GetFirstDateInWeek(DateTime date, DayOfWeek firstDayOfWeek)
- {
- int diffNum = ((int)(date.DayOfWeek - firstDayOfWeek) + 7) % 7;
- return date.AddDays(-1 * diffNum);
- }
- /// <summary>
- /// 取得本周的最后一天的日期
- /// </summary>
- /// <param name="date">日期</param>
- /// <param name="firstDayOfWeek">星期的第一天是星期几,周一或者周日</param>
- /// <returns></returns>
- public static DateTime GetLastDateInWeek(DateTime date, DayOfWeek firstDayOfWeek)
- {
- int diffNum = ((int)(date.DayOfWeek - firstDayOfWeek) + 7) % 7;
- return date.AddDays(7 - diffNum - 1);
- }
- /// <summary>
- /// 取得本年中的周数
- /// </summary>
- /// <param name="date">日期</param>
- /// <param name="firstDayOfWeek">星期的第一天是星期几,周一或者周日</param>
- /// <returns></returns>
- public static int GetWeekNumberInYear(DateTime date, DayOfWeek firstDayOfWeek)
- {
- return (GetLastDateInWeek(date, firstDayOfWeek).DayOfYear - 1) / 7 + 1;
- }
- #endregion
- #region 字符串转换成日期
- /// <summary>
- /// 字符串转换成日期
- /// </summary>
- /// <param name="dateTimeString">需要转换成日期的字符串</param>
- /// <param name="dateTime">返回转换后的日期</param>
- /// <returns>
- /// True:转换成功
- /// False:转换错误
- /// </returns>
- public static bool ConvertDateTime(string dateTimeString, out DateTime dateTime)
- {
- return ConvertDateTime(dateTimeString, null, out dateTime);
- }
- /// <summary>
- /// 字符串转换成日期
- /// </summary>
- /// <param name="dateTimeString"></param>
- /// <param name="parseList"></param>
- /// <param name="dateTime">返回转换后的日期,转换失败的情况下,返回DateTime.MinValue</param>
- /// <returns>
- /// True:转换成功
- /// False:转换错误
- /// </returns>
- public static bool ConvertDateTime(string dateTimeString, string[] parseList, out DateTime dateTime)
- {
- if (string.IsNullOrEmpty(dateTimeString))
- {
- dateTime = DateTime.MinValue;
- return false;
- }
- string parseFormat = GetDateTimeParseFormat(dateTimeString, parseList);
- if (string.IsNullOrEmpty(parseFormat))
- {
- dateTime = DateTime.MinValue;
- return false;
- }
- dateTimeString = ConvertDelimiter(dateTimeString);
- string yearStr, month, day, hour, minute, second;
- yearStr = ExtractSubstring(dateTimeString, parseFormat, string.Empty, "YYYY", "YY");
- if (yearStr.Length == 2)
- {
- // 西历的年是2位的情况,需要自动补充完整
- string paramYearUnderStr = yearStr;
- int nParamYearUnder = int.Parse(paramYearUnderStr);
- // 现在系统的时间
- string curYearStr;
- curYearStr = DateTime.Today.Year.ToString();
- int curYearUpper = int.Parse(curYearStr.Substring(0, 2));
- int curYearUnder = int.Parse(curYearStr.Substring(2, 2));
- int border = curYearUnder - 50;
- int year1, year2;
- if (border < 0)
- {
- // 当前西历是上半年的情况
- border = curYearUnder + 50;
- year1 = curYearUpper;
- year2 = curYearUpper - 1;
- }
- else
- {
- // 当前西历是是下半年的情况
- year1 = curYearUpper + 1;
- year2 = curYearUpper;
- }
- string tmpStr;
- tmpStr = ((nParamYearUnder <= border) ? year1 : year2).ToString();
- tmpStr += paramYearUnderStr;
- yearStr = tmpStr;
- }
- // 月
- month = ExtractSubstring(dateTimeString, parseFormat, "1", "MMM", "MM", "M");
- if (month.Length == 3)
- {
- // [JAN/FEB/...]的情况
- month = ConvertValue(EMONTH_LIST, month);
- }
- // 日
- day = ExtractSubstring(dateTimeString, parseFormat, "1", "DD", "D");
- // 小时
- hour = ExtractSubstring(dateTimeString, parseFormat, "0", "hh", "h");
- // 分钟
- minute = ExtractSubstring(dateTimeString, parseFormat, "0", "mm", "m");
- // 秒
- second = ExtractSubstring(dateTimeString, parseFormat, "0", "ss", "s");
- bool isFindYear = true;
- if (string.IsNullOrEmpty(yearStr))
- {
- // 是不是能够找到年度
- isFindYear = false;
- // 用当前年度设定
- yearStr = DateTime.Today.Year.ToString();
- }
- try
- {
- // 向日期类型进行转换
- DateTime tmp = DateTime.MinValue;
- if (DateTime.TryParse(string.Format("{0}/{1}/{2} {3}:{4}:{5}", yearStr, month, day, hour, minute, second), out tmp))
- {
- dateTime = tmp;
- }
- else
- {
- dateTime = DateTime.MinValue;
- return false;
- }
- }
- catch (Exception)
- {
- dateTime = DateTime.MinValue;
- return false;
- }
- if (isFindYear == false)
- {
- if (dateTime < DateTime.Today)
- {
- dateTime = dateTime.AddYears(1);
- }
- }
- return true;
- }
- #endregion
- #region 日期转换成字符串
- public static string ConvertString(DateTime source, string format)
- {
- string result = format;
- // 日期·时间的变量初始化
- string year = string.Format("{0:0000}", source.Year);
- string month = string.Format("{0:00}", source.Month);
- string day = string.Format("{0:00}", source.Day);
- string hour = string.Format("{0:00}", source.Hour);
- string minute = string.Format("{0:00}", source.Minute);
- string second = string.Format("{0:00}", source.Second);
- // 向指定格式的数据进行转换
- result.Replace("YYYY", year);
- result.Replace("YY", year.Substring(2, 2));
- result.Replace("MMM", EMONTH_LIST[int.Parse(TrimLeftZero(month)) - 1].Substring(0, 3).ToUpper());
- result.Replace("MM", month);
- result.Replace("M", TrimLeftZero(month));
- result.Replace("DD", day);
- result.Replace("D", TrimLeftZero(day));
- result.Replace("hh", hour);
- result.Replace("h", TrimLeftZero(hour));
- result.Replace("mm", minute);
- result.Replace("m", TrimLeftZero(minute));
- result.Replace("ss", second);
- result.Replace("s", TrimLeftZero(second));
- result.Replace("ddd", EWDAY_LIST[(source.DayOfWeek - DayOfWeek.Sunday) - 1].Substring(0, 3).ToUpper());
- result.Replace("dd", EWDAY_LIST[(source.DayOfWeek - DayOfWeek.Sunday) - 1].Substring(0, 2).ToUpper());
- result.Replace("jjj", CWDAY_LIST[(source.DayOfWeek - DayOfWeek.Sunday) - 1]);
- result.Replace("j", CWDAY_LIST[(source.DayOfWeek - DayOfWeek.Sunday) - 1].Substring(0, 1));
- return result;
- }
- #endregion
- #region 年龄·月龄计算
- /// <summary>
- /// 计算年龄
- /// </summary>
- /// <param name="birthDate">生日</param>
- /// <param name="baseDate">计算日期</param>
- /// <returns></returns>
- public static int CalcAge(DateTime birthDate, DateTime baseDate)
- {
- // 基本年龄
- int age = baseDate.Year - birthDate.Year;
- // 当年的生日
- DateTime thisYearBirthDate = birthDate.AddYears(age);
- // 生日前判断
- if (baseDate < thisYearBirthDate)
- {
- age--;
- }
- return age;
- }
- /// <summary>
- /// 计算月龄
- /// </summary>
- /// <param name="birthDate">生日</param>
- /// <param name="baseDate">计算日期</param>
- /// <returns></returns>
- public static int CalcAgeMonth(DateTime birthDate, DateTime baseDate)
- {
- // 基本月龄
- int ageMonth = (baseDate.Year - birthDate.Year) * 12
- + (baseDate.Month - birthDate.Month);
- // 生日前判断
- if (baseDate.Day < birthDate.Day)
- {
- ageMonth--;
- }
- return ageMonth;
- }
- #endregion
- #endregion
- #region 私有函数/方法
- /// <summary>
- /// 指定的字符串按照规定的格式要求转换成日期格式
- /// </summary>
- /// <param name="dateTime"></param>
- /// <param name="formatList"></param>
- /// <returns></returns>
- private static string GetDateTimeParseFormat(string dateTime, string[] formatList)
- {
- dateTime = ConvertDelimiter(dateTime);
- if (formatList == null)
- {
- System.Collections.Generic.List<string> list =
- new System.Collections.Generic.List<string>();
- foreach (string format in FORMAT_LIST_FOR_DATE)
- {
- list.Add(format);
- }
- foreach (string format in FORMAT_LIST_FOR_TIME)
- {
- list.Add(format);
- }
- foreach (string formatDate in FORMAT_LIST_FOR_DATE)
- {
- foreach (string formatTime in FORMAT_LIST_FOR_TIME)
- {
- list.Add(string.Format("{0}_ _{1}", formatDate, formatTime));
- }
- }
- formatList = list.ToArray();
- }
- int start, end, checkNum;
- bool isMatch;
- string formatTemp, item, type;
- string parseFormat = null;
- for (int i = 0; i < formatList.Length; i++)
- {
- formatTemp = formatList[i];
- formatTemp = formatTemp.Replace("_", string.Empty);
- if (formatTemp.Length != dateTime.Length)
- {
- continue;
- }
- formatTemp = formatList[i];
- start = end = checkNum = 0;
- isMatch = true;
- while (0 <= end)
- {
- end = formatTemp.IndexOf("_", end);
- if (0 <= end)
- {
- item = dateTime.Substring(start - checkNum, end - start);
- type = formatTemp.Substring(start, end - start);
- }
- else
- {
- item = dateTime.Substring(start - checkNum);
- type = formatTemp.Substring(start);
- }
- if (!CheckItem(item, type))
- {
- isMatch = false;
- break;
- }
- if (end < 0)
- {
- break;
- }
- checkNum++;
- start = ++end;
- }
- if (isMatch)
- {
- parseFormat = formatTemp;
- break;
- }
- }
- if (string.IsNullOrEmpty(parseFormat))
- {
- // 不可识别的情况
- return null;
- }
- else
- {
- // 取得显示的格式
- return parseFormat.Replace("_", string.Empty);
- }
- }
- /// <summary>
- /// 分隔符替换
- /// </summary>
- /// <param name="dateTime"></param>
- /// <returns></returns>
- private static string ConvertDelimiter(string dateTime)
- {
- return Regex.Replace(dateTime, "[^A-Za-z0-9_ ]", "/");
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="list"></param>
- /// <param name="value"></param>
- /// <returns></returns>
- private static string ConvertValue(string[] list, string value)
- {
- if (string.IsNullOrEmpty(value))
- {
- return null;
- }
- int length = value.Length;
- for (int i = 0; i < list.Length; i++)
- {
- if (value.Equals(list[i].Substring(0, length),
- StringComparison.InvariantCultureIgnoreCase))
- {
- return string.Format("{0:00}", i + 1);
- }
- }
- return null;
- }
- /// <summary>
- /// 字符串的值是不是该种类的检查
- /// </summary>
- /// <param name="item"></param>
- /// <param name="type"></param>
- /// <returns></returns>
- private static bool CheckItem(string item, string type)
- {
- if ("/".CompareTo(type) == 0)
- {
- // 有日期分隔符的情况
- if ("/".CompareTo(item) == 0)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- else if (" ".CompareTo(type) == 0)
- {
- // 空字符串的情况
- if (" ".CompareTo(item) == 0)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- else if ("MMM".CompareTo(type) == 0)
- {
- // [JAN/FEB/...]格式的情况
- return !string.IsNullOrEmpty(ConvertValue(EMONTH_LIST, item));
- }
- else
- {
- // 月份是通常数字的情况
- if (type.Length != item.Length)
- {
- return false;
- }
- int result;
- return int.TryParse(item, out result);
- }
- }
- /// <summary>
- /// 提取该字符串
- /// </summary>
- /// <param name="dateTimeString"></param>
- /// <param name="parseFormat"></param>
- /// <param name="defaultValue"></param>
- /// <param name="findList"></param>
- /// <returns></returns>
- private static string ExtractSubstring(string dateTimeString, string parseFormat,
- string defaultValue, params string[] findList)
- {
- int index;
- foreach (string find in findList)
- {
- if ((index = parseFormat.IndexOf(find)) != -1)
- {
- return dateTimeString.Substring(index, find.Length);
- }
- }
- return defaultValue;
- }
- /// <summary>
- /// 左边用零补齐
- /// </summary>
- /// <param name="value"></param>
- /// <returns></returns>
- private static string TrimLeftZero(string value)
- {
- if (string.IsNullOrEmpty(value))
- {
- return value;
- }
- return value.TrimStart(new char[] { '0' });
- }
- #endregion
- }
- }
|