C#时间日期格式练习 -009

示例1:获取当前日期是星期几

技术
DateTime.Now.ToString();

实现

public void GetWeek()
{
    Console.WriteLine(DateTime.Now.ToString("dddd"));//星期
    Console.WriteLine(DateTime.Now.ToString("MMM"));//月 
    Console.WriteLine(DateTime.Now.ToString("dd"));//号
    Console.WriteLine(DateTime.Now.ToString("yyyy"));//年
}

总结
DateTime详解
https://www.cnblogs.com/tmdsleep/p/5700058.html

示例2:获取当年的天数

技术
计算两个时间差值
DateTime dt1 = Convert.ToDateTime(“2007-8-1”);
DateTime dt2 = Convert.ToDateTime(“2007-8-15”);
TimeSpan span = dt2.Subtract(dt1);
int dayDiff = span.Days ;

实现

public string GetDay()
{
    int year = DateTime.Now.Year;
    int month = DateTime.Now.Month;
    int day = DateTime.Now.Day;
    int present = 0;
    if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
    {
        present = 365;
    }
    else
    {
        present = 364;
    }
    //当年剩余时间
    DateTime dt1 = Convert.ToDateTime(year + "-" + month + "-" + day);
    DateTime dt2 = Convert.ToDateTime(year + "-12-31");
    TimeSpan span = dt2.Subtract(dt1);
    return year + "年有" + present + "天;" + "当年剩余:" + span.Days + "天";
}

总结
DateTime详解
https://www.cnblogs.com/tmdsleep/p/5700058.html

示例3:格式化日期为指定模式

技术
yyyy/MM/dd HH:mm:ss

实现

public void FormatDate()
{
    DateTime dt = DateTime.Now;
    // yyyy/MM/dd HH:mm:ss  2021/11/14 11:28:05
    Console.WriteLine(dt.ToString("yyyy/MM/dd HH:mm:ss"));
}

总结
DateTime详解
https://www.cnblogs.com/tmdsleep/p/5700058.html

  • 时间:2021.11.7
  • 完成:2021.11.14

你可能感兴趣的:(实战练习,c#)