時間通用類 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;
        }
        
    }
相關文章
相關標籤/搜索