鼎鼎知识库
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

19.C#中关于时间.md 2.4KB

关于年的问题

  • DownList显示年,可根据当前的年份,具体代码 public List<string> GetYears() { List<string> allYears = new List<string>(); var now = DateTime.Now; int currentYear = now.Year;//2019 allYears.Add((currentYear - 3).ToString());//2016 allYears.Add((currentYear - 2).ToString());//2017 allYears.Add((currentYear - 1).ToString());//2018 allYears.Add(currentYear.ToString());//2019 allYears.Add((currentYear + 1).ToString());//2020 allYears.Add((currentYear + 2).ToString());//2021 allYears.Add((currentYear + 3).ToString());//2022 return allYears; }

关于月的问题

  • DownList显示月。因为月是具体的24个月,可直接增添值 public List<string> GetMonths() { List<string> allMonths = new List<string>(); allMonths.AddRange(new List<string> { "01","02","03","04","05","06","07","08","09","10","11","12"}); return allMonths; }

关于天的问题

  • 因为每年的每个月的天数不确定,可以根据请求或者选择的年月进行显示天数

    /// <summary>
        /// 获取天
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <returns></returns>
        public List<string> GetDays(string year, string month)
        {
            var result = new List<string>();
    
            if(!string.IsNullOrEmpty(year) && !string.IsNullOrEmpty(month))
            {
                //拼接月和年 2019-04
                string yearAndMonthStr = year + "-" + month;
                //月初 2019-04-01
                DateTime beginTime = DateTime.Parse(yearAndMonthStr + "-01");
                DateTime endTime = DateTime.Parse(beginTime.AddMonths(1).AddDays(-1).ToShortDateString());
                //月末
                for (DateTime dt = beginTime; dt <= endTime; dt = dt.AddDays(1))
                {
                    result.Add(dt.Day.ToString());
                }
            }
                
            return result;
        }
    

    时间格式转换(12或者24小时) ``` string time = Convert.ToDateTime(date).ToString(“yyyy-MM-dd HH:mm”);//HH为24小时 string time = Convert.ToDateTime(date).ToString(“yyyy-MM-dd hh:mm”);//hh为12小时

```