根据年和当前年的第几天,获取年月日字符串

 

        /// <summary>
        /// 根据年和当前年的第几天,获取年月日字符串
        /// </summary>
        /// <param name="Year"></param>
        /// <param name="Days"></param>
        /// <returns></returns>
        public string GetCurrentYearForDays(int Year, int Days)
        {
            ///二月,闰年 28年,其他 29天
            int ErYueDays = Year % 4 == 0 ? 28 : 29; ;
            ///小月 30天
            int XiaoYueDays = 30;
            ///大月 31天
            int DaYueDays = 31;

            ///一年中大月的月份
            int[] DY = { 1, 3, 5, 7, 8, 10, 12 };
            ///一年中小月的月份
            int[] XY = { 4, 6, 9, 11 };
            ///一年中二月的月份
            int[] EY = { 2 };

            int O_Year = 0, O_Mouth = 0, O_Day = 0;

            try
            {
                O_Year = Year;

                ///直到上个月的累积天数
                int LastMouthDay = 0;

                ///十二个月
                for (int i = 1; i <= 12; i++)
                {
                    int MouthDays = 0;
                    if (DY.Contains(i)) MouthDays = DaYueDays;
                    if (XY.Contains(i)) MouthDays = XiaoYueDays;
                    if (EY.Contains(i)) MouthDays = ErYueDays;

                    ///判断是否是当前月
                    if (LastMouthDay + MouthDays >= Days)
                    {
                        O_Mouth = i;
                        O_Day = Days - LastMouthDay;
                        LastMouthDay += MouthDays;
                        break;
                    }
                    else
                    {
                        LastMouthDay += MouthDays;
                    }
                }

                ///如果超过最大天数,则返回为空
                if (LastMouthDay < Days)
                {
                    O_Year = 0;
                    O_Mouth = 0;
                    O_Day = 0; 
                    return "";
                }
            }
            catch (Exception)
            {

                throw;
            }

            return string.Format("{0}-{1}-{2}", O_Year.ToString().PadLeft(4, '0'), O_Mouth.ToString().PadLeft(2, '0'), O_Day.ToString().PadLeft(2, '0'));
        }

  

posted @ 2018-03-09 12:14  人生为卒  阅读(760)  评论(0编辑  收藏  举报