注册 登录
编程论坛 C# 论坛

请教 c# 时间处理问题

黑客18岁 发布于 2016-04-02 10:53, 1842 次点击
各位高手,请问如何让c#自动转换时间。
例如dt=DateTime(2006, 5, 32);
  因为5月没有32日,但我想让它自动转成 6月1日,如何做??
 谢谢!
2 回复
#2
qq10235692232016-04-02 12:51
程序代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int y = 2006, m = 12, d = 32;
            Console.WriteLine("{0}-{1}-{2}", y, m, d);

            fun(ref y, ref m, ref d);

            Console.WriteLine("{0}-{1}-{2}", y, m, d);

            Console.ReadKey();
        }

        //使用一个方法来变换年月日
        private static void fun(ref int year,ref int month,ref int day)
        {
            int[] days = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };  //每月的天数

            if(year%400==0||(year%4==0&&year%100!=0))  //闰年2月29天
            {
                days[1] = 29;
            }

            if (day <= days[month - 1]) return;  //天数不超过当月的天数,直接返回
            
            if(month==12)  //如果是12月,则要转到明年的1月
            {
                year += 1;
                month = 1;
                day -= 31;
            }
            else  //一般的情况
            {
                day -= days[month - 1];
                month += 1;
            }
        }
    }
}
#3
黑客18岁2016-04-02 15:33
谢谢! 因为存在其他可能,例如:DateTime(2015,16,36),所以考虑的问题还是挺多的。后来引用的一个函数可以统一解决。
1