【C#】DATETIME心得
1.yyyyMMdd的字串轉DateTime
或
2.常用函數
1
| var newDate = DateTime.ParseExact("20111120", "yyyyMMdd", CultureInfo.InvariantCulture); |
1
2
3
4
5
6
7
8
| string str = "20111021";string[] format = {"yyyyMMdd"};DateTime date;if (DateTime.TryParseExact(str, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out date)){ //valid} |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
| C# 常用日期時間函數(老用不熟) ,需要的朋友可以參考下。//取當前年月日時分秒currentTime=System.DateTime.Now;//取當前年int 年=currentTime.Year;// 取當前月int 月=currentTime.Month;// 取當前日int 日=currentTime.Day;// 取當前時int 時=currentTime.Hour;//取當前分int 分=currentTime.Minute;// 取當前秒int 秒=currentTime.Second;// 取當前毫秒int 毫秒=currentTime.Millisecond;// 取中文日期顯示——年月日時分string strY=currentTime.ToString("f"); //不顯示秒// 取中文日期顯示_年月string strYM=currentTime.ToString("y");//取中文日期顯示_月日string strMD=currentTime.ToString("m");// 取當前年月日,格式為:2003-9-23string strYMD=currentTime.ToString("d");// 取當前時分,格式為:14:24string strT=currentTime.ToString("t");//今天DateTime.Now.Date.ToShortDateString();//昨天,就是今天的日期減一DateTime.Now.AddDays(-1).ToShortDateString();//明天DateTime.Now.AddDays(1).ToShortDateString();//本周(要知道本周的第一天就得先知道今天是星期幾,從而得知本周的第一天就是幾天前的//那一天,要注意的是這裏的每一周是從周日始至週六止DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(DateTime.Now.DayOfWeek)))).ToShortDateString();DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(DateTime.Now.DayOfWeek)))).ToShortDateString();//如果你還不明白,再看一下中文顯示星期幾的方法就應該懂了//由於DayOfWeek返回的是數字的星期幾,我們要把它轉換成漢字方便我們閱讀,有些人可能會用switch來一個一個地對照,其實不用那麼麻煩的 string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };Day[Convert.ToInt16(DateTime.Now.DayOfWeek)];//上周,同理,一個周是7天,上周就是本周再減去7天,下周也是一樣DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(DateTime.Now.DayOfWeek))) - 7).ToShortDateString();DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(DateTime.Now.DayOfWeek))) - 7).ToShortDateString();//下周DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(DateTime.Now.DayOfWeek))) + 7).ToShortDateString();DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(DateTime.Now.DayOfWeek))) + 7).ToShortDateString();//本月,很多人都會說本月的第一天嘛肯定是1號,最後一天就是下個月一號再減一天。當然//這是對的//一般的寫法DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "1"; //第一天DateTime.Parse(DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "1").AddMonths(1).AddDays(-1).ToShortDateString();//最後一天 |
沒有留言:
張貼留言