可直接拷贝到控制台程序运行
一、基础Demo
class Test
{
public static bool IsWeekend(DateTime date)//判断是否周末
{
return date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday;
}
private static string GetLastDate(int year, int month)//根据年月获取最后一天的年月日
{
DateTime lastDayOfMonth = new DateTime(year, month, DateTime.DaysInMonth(year, month));
string lastDay = lastDayOfMonth.ToString("yyyy-MM-dd");
return lastDay;
}
static void Main(string[] args)
{
//1.格式化
//(1)字符串转日期
DateTime dateTime = DateTime.Parse("2023-11-11");//也可以写成2023/11/08格式,转换结果:2023/11/11 0:00:00
//高级写法(统一各国时间输出格式):
//DateTime dateTime_2 = DateTime.ParseExact("2023-11-11", "yyyy-MM-dd", CultureInfo.InvariantCulture);
//(2)日期转字符串
string dateTimenow = DateTime.Now.ToString("yyyy/MM-dd");//2023/11-17
//2.年月日时分秒
int d1 = dateTime.Year;
int d2 = dateTime.Month;
int d3 = dateTime.Day;
int d4 = dateTime.Hour;
int d5 = dateTime.Minute;
int d6 = dateTime.Second;
DateTime resulttime = dateTime.Date;//打印完整日期:2023/11/11 0:00:00
string resulttime2 = dateTime.ToShortDateString();//打印短日期:2023/11/11
string resulttime3 = dateTime.ToShortTimeString();//打印短时间:0:00
string resulttime4 = dateTime.ToLongTimeString();//打印长时间:0:00:00
string resulttime5 = dateTime.ToLongDateString();//打印长时间:2023年11月11日
//3.修改时间
//修改前
DateTime d7 = DateTime.Parse("2024-01-01 12:00:00");//2024/1/1 12:00:00
// 修改年、月、日
DateTime d7_1 = new DateTime(2025, 02, 03, d7.Hour, d7.Minute, d7.Second, DateTimeKind.Local);//2025/2/3 12:00:00
// 修改时、分、秒
DateTime d7_2 = new DateTime(d7.Year, d7.Month, d7.Day, 15, 30, 45, DateTimeKind.Local);//2025/2/3 15:30:45
//4.日期计算
DateTime d8 = DateTime.Now;//获取今天日期
DateTime d9 = dateTime.AddDays(1);//增加一天
DateTime d10 = dateTime.AddDays(-1);//减少一天
//5.判断是否为周末
bool isWeekend = IsWeekend(dateTime.Date);//True
//6.比较时间早晚(越晚越大)
Console.WriteLine(DateTime.Parse("2023-12-01") > DateTime.Parse("2024-12-01"));//输出false
//7.通过某年某月判断最后一天的日期,例如输入2022-02,返回2022-02-28;2024-02,返回2024-02-29;
string lastDay = GetLastDate(2024, 02);
Console.WriteLine(lastDay);
//8.判断时间是否是默认值"0001-01-01 00:00:00"
//若b=true则该时间是默认值
DateTime d11 = DateTime.Parse("0001-01-01 00:00:00");
bool b = d11 == DateTime.MinValue;
Console.WriteLine(b);
}
}
二、小结
1.建议使用DateTime ?,而不是DateTime
- 使用可空类型:前端入参的时间格式化错误,就会转化为null,而不是转化为0001/1/1 0:00:00(DateTime会转化为这种格式)
- 两种类型:均支持多种格式传入:年月、年月日、年月日时分、年月日时分秒(分隔符支持 - / )
2.日期默认值赋null的问题
【要求】时间为默认值“0001/1/1 0:00:00”时赋为null
【易错点】三元运算符不能直接赋null,要写成(DateTime?)null
var result = datetime == DateTime.MinValue? null : datetime;//报错,三元运算符前后类型要匹配
var result = datetime == DateTime.MinValue? (DateTime?)null : datetime;//正确