时间通用类 datetime

/// <summary>
    /// 时间通用类
    /// </summary>
    public class DateTimeGeneral
    {
        /// <summary>
        /// 获取unix时间
        /// </summary>
        /// <returns></returns>
        public static int GetUnixTime()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt32(ts.TotalSeconds);
        }
        /// <summary>
        /// 获取unix时间
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public static int GetUnixTime(DateTime t)
        {
            TimeSpan ts = t - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt32(ts.TotalSeconds);
        }
        public static DateTime DateIntToDateTime(int dateInt)
        {
            try
            {

                return DateTime.ParseExact(dateInt.ToString(), "yyyyMMdd", System.Globalization.DateTimeFormatInfo.CurrentInfo);
            }
            catch {
                return DateTime.Now;
            }
        }
        /// <summary>
        /// 根据按日,按周,按月等方式获取相关的名字
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="dateMode"></param>
        /// <returns></returns>
        public static string GetCategoriesName(DateTime dt, Enums.ReportChartsDateModeEnum dateMode)
        {
            string r = "";
            switch (dateMode)
            {
                case Enums.ReportChartsDateModeEnum.ForDay:
                    r = dt.ToString("yyyy-MM-dd");
                    break;
                case Enums.ReportChartsDateModeEnum.ForWeek:
                    //计算日期是第几周:
                    
                    int weekOfYear =  WeekOfYear(dt);
                    r = "" + weekOfYear + "";
                    break;
                case Enums.ReportChartsDateModeEnum.ForMonth:
                    r = dt.Month + "";
                    break;
                default:
                    r = dt.ToString("yyyy-MM-dd");
                    break;
            }

            return r;
        }
        /// <summary>
        /// 获取一年中的第几周
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static int WeekOfYear(DateTime dt)
        {
            GregorianCalendar gc = new GregorianCalendar(GregorianCalendarTypes.Localized);
            int weekOfYear = gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
            return weekOfYear;
        }
        
    }

 

posted @ 2018-07-02 11:43  青山下  阅读(138)  评论(0编辑  收藏  举报