c # datetime


1. Get the current time

We can get the current time by using the DataTime class. We can get different times by calling various methods in the class: such as: date (2008-09-04), time (12:12:12), date+time (2008-09-04 12:11:10) Wait.


1.1 C# get time

//获取日期+时间
DateTime.Now.ToString();            // 2008-9-4 20:02:10
DateTime.Now.ToLocalTime().ToString();        // 2008-9-4 20:12:12
//获取日期
DateTime.Now.ToLongDateString().ToString();    // 2008年9月4日
DateTime.Now.ToShortDateString().ToString();    // 2008-9-4
DateTime.Now.ToString("yyyy-MM-dd");        // 2008-09-04
DateTime.Now.Date.ToString();            // 2008-9-4 0:00:00
//获取时间
DateTime.Now.ToLongTimeString().ToString();   // 20:16:16
DateTime.Now.ToShortTimeString().ToString();   // 20:16
DateTime.Now.ToString("hh:mm:ss");        // 08:05:57
DateTime.Now.TimeOfDay.ToString();        // 20:33:50.7187500
//其他
DateTime.ToFileTime().ToString();       // 128650040212500000
DateTime.Now.ToFileTimeUtc().ToString();   // 128650040772968750
DateTime.Now.ToOADate().ToString();       // 39695.8461709606
DateTime.Now.ToUniversalTime().ToString();   // 2008-9-4 12:19:14
DateTime.Now.Year.ToString();         获取年份  // 2008
DateTime.Now.Month.ToString();      获取月份   // 9
DateTime.Now.DayOfWeek.ToString(); 获取星期   // Thursday
DateTime.Now.DayOfYear.ToString(); 获取第几天   // 248
DateTime.Now.Hour.ToString();          获取小时   // 20
DateTime.Now.Minute.ToString();     获取分钟   // 31
DateTime.Now.Second.ToString();     获取秒数   // 45
//n为一个数,可以数整数,也可以事小数
dt.AddYears(n).ToString();   //时间加n年
dt.AddDays(n).ToString();   //加n天
dt.AddHours(n).ToString();   //加n小时
dt.AddMonths(n).ToString();   //加n个月
dt.AddSeconds(n).ToString();   //加n秒
dt.AddMinutes(n).ToString();   //加n分

1.2 sql statement

getdate():获取系统当前时间
dateadd(datepart,number,date):计算在一个时间的基础上增加一个时间后的新时间值,比如:dateadd(yy,30,getdate())
datediff(datepart,startdate,enddate):计算两个时间的差值,比如:datediff(yy,getdate(),'2008-08-08')
dataname(datepart,date):获取时间不同部分的值,返回值为字符串
datepart(datepart,date):和datename相似,只是返回值为整型
day(date):获取指定时间的天数
month(date):获取指定时间的月份
year(date):获取指定时间的年份
select year(getdate()) :当前年份




2. String conversion

------解决方案--------------------------------------------------------
DateTime.Now.ToShortDateString()
------解决方案--------------------------------------------------------
convert(char(20),时间,111) as 时间
------解决方案--------------------------------------------------------
.ToShortDateString();
------解决方案--------------------------------------------------------
datetime.ToString( "yyyy-MM-dd ");
------解决方案--------------------------------------------------------
DateTime.Now.ToShortDateString()
或者用楼上的方法
------解决方案--------------------------------------------------------
str = dt.ToString( "yyyy-M-d ");
------解决方案--------------------------------------------------------
public string formatdatetime(string date)
{
    
    
DateTime dt = DateTime.Parse(date);
return dt.ToString( "yyyy年MM月dd日 ");
}

We use DateTime.Pares() when dealing with string date formats, but the conversion of this form is quite limited. Some C# will not understand the date format you write, such as 20031231. So how to convert a string like "20100101" or other forms into a date type?

In direct new

DateTime actualTime =new  DateTime(2020,8,1),

One, the form of splicing strings

DateTime dt=Convert.ToDateTime("20100101".Substring(0,4)+
"-"+"20100101".Substring(4,2)
+"-"+"20071107".Substring(6,2)); 

二、Convert.ToDateTime(string)

string格式有要求,必须是yyyy-MM-dd hh:mm:ss 

三、Convert.ToDateTime(string, IFormatProvider)

DateTime dt;

DateTimeFormatInfo dtFormat = new System.GlobalizationDateTimeFormatInfo();

dtFormat.ShortDatePattern = "yyyy/MM/dd";

dt = Convert.ToDateTime("2011/05/26", dtFormat);

四、DateTime.ParseExact()

string dateString = "20110526";

DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);

//或者

DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);

五、DateTime.TryParse(string,out datetime)

1、更多时候,会采用DateTime.TryParse(string,out datetime)方法,因为此方法有安全机制,当string内容不正确时,可以返回日期的最小值MinValue。并且可以通过返回的bool值判断转化是否成功。

2.而DateTime.ParseExact()需要按特定的格式来转换,对格式的要求比较严,如果string中不是日期内容,而量类似“asdfasd”的字符串,则会出错。

3、用DateTime.TryParse(string,out datetime)转换后,得到的datetime可以用 datetime.ToString("ddd, MMM. dd")来转换为特殊需求的格式,比较灵活方便。

6. Go to a fixed point in time

Go to five o'clock in the morning of the next day

 var mm = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-d 05:00:00")).AddDays(1);



Three. Directly through the string conversion

Various date formats of DateTime.ToString()

Example:

ToString:2016/9/27 0:00:00
ToString(“yyyy/MM/dd”):2016/09/27
ToString(“yyyy-MM-dd”):2016-09-27
ToString(“yyyy.MM.dd”):2016.09.27
ToString(“dd/MM/yyyy”):27/09/2016
ToString(“dd-MM-yyyy”):27-09-2016
ToString(“yyyy年MM月dd日”):2016年09月27日

ToString("yyyy-MM-dd HH:mm:ss.fff")); 2016-09-27 01:02:03.001 // The more fff, the higher the accuracy

ToString(“yyyy-MM-dd HH:mm:ss:ms”)); 2016-09-27 01:02:03:234


explain in detail:

1. y represents the year, note that the lowercase y, the uppercase Y does not represent the year.

2. M represents the month.

3. d represents the date, note that D does not represent anything.

4. h or H means hour, h uses a 12-hour system, and H uses a 24-hour system.

5. m means minutes.

6.s means seconds. Note that S does not mean anything.





4. Uniform restrictions on the time format in webapi

In Startupthe following ways prescribed class

  services.AddControllers().AddNewtonsoftJson(options =>
            {
    
    
                options.SerializerSettings.DateFormatString = "MM月dd日";//设置时间格式
            });        

references

[1] https://www.cnblogs.com/lushousong/p/3277302.html
[2] http://www.cnblogs.com/spring_wang/
[3] http://blog.163.com/ljq086@ 126/blog/static/549639712010112921658843/
[4] Microsoft official website
[5] https://www.cnblogs.com/johnblogs/p/5912632.html

Guess you like

Origin blog.csdn.net/zhaozhao236/article/details/111399748