c#基础三 常用数据类型的用法(DateTime类 Math类 Random类)

六:日期与时间处理

对日期和事件处理的常用类为DateTime类 和 TimeSpan类。

  • DateTime类表示范围在0001年1月1日午夜12:00:00到9999年12月31日晚上11:59:59之间的日期,最小时间单位等于100ns.
  • TimeSpan类表示一个时间间隔,其范围在Int64.MinValue到Int64.MaxValue之间

下面的代码演示DateTime类的使用方法:

View Code
 1 using System;
2 //using System.Collections.Generic;
3 //using System.Linq;
4 //using System.Text;
5
6 namespace 日期与时间处理
7 {
8 class Program
9 {
10 static void Main(string[] args)
11 {
12 //DateTime一共有12种构造函数 以下为常用的几种
13 DateTime dt1 = new DateTime
14 (2012,//
15 03,//
16 01,//
17 23,//
18 02,//
19 30,//
20 12//毫秒
21 );
22 DateTime dt2 = new DateTime(2012, 2, 11);
23 //此处F的作用是按年月日格式输出,记得之前是F代表小数点后两位的格式,也不清楚怎么变成年月日了(注意两变的格式):
24 //输出 2012年3月1日 23:02:30---2012-2-11 0:00:00
25 Console.WriteLine("{0:F}---{1}", dt1, dt2);
26
27 dt1 = DateTime.Now;//获取当前时间
28 int i = dt1.Day;//当月第几天
29 int j = dt1.Month;//
30 int k = dt1.Year;//
31 int l = dt1.Hour;//小时
32 //输出:当前时间2012-3-2 0:02:05---对应的小时:0---对应的天:2---对应的月:3---对应的年:2012
33 Console.WriteLine("当前时间:{0}---对应的小时:{4}---对应的天:{1}---对应的月:{2}---对应的年:{3}", dt1, i, j, k,l);
34
35 DateTime t1 = dt1.Date;//日期部分
36 Console.WriteLine(t1);
37
38 TimeSpan ts1 = dt1.TimeOfDay;//当天的时间
39 TimeSpan ts2 = dt1 - dt2;
40 i = ts2.Days;
41 //输出:00:04:29:4218750---20.00.04.29.4218750---20
42 Console.WriteLine("{0}---{1}---{2}",ts1,ts2,i);
43
44 string s1 = dt1.ToLongDateString();
45 string s2 = dt2.ToShortDateString();
46 string s3 = string.Format("{0:yyyy.MM.dd}",dt1);
47 //输出:2012-3-2 0:13:26--2012年3月2日---2012.3.2
48 Console.WriteLine("{0}--{1}--{2}--{3}",dt1,s1,s2,s3);
49 //输出:现在是2012年3月2日,0点18分,星期五
50 string str = string.Format("{0:现在是yyyy年M月d日,H点m分,dddd}",dt1);
51 Console.WriteLine(str);
52
53
54 Console.ReadLine();
55 }
56 }
57 }

七:数学运算

 

 Math类提供了各种常用的数学运算,位于System命名空间下。作用:

 1.为三角函数、对数函数和其他通用函数提供常数,如PI值

 2.提供各种数学运算的静态方法:
  Math.Abs(-5);//求绝对值 5
  Math.Ceiling(2.7);//大于等于2.7的最小整数为3
  Math.Floor(2.7);//小于等于2.7的最大整数为2
  Math.Max(10,-5);//10和-5的较大者为10
  Math.Pow(2,5);//2的5次方为32
  Math.Round(1.3);//1.3的四舍五入值为1
  Math.Round(4.5);//4.5的四舍五入值为4
  Math.Round(5.5);//6
  Math.Sqrt(5);//5的平方根为2.23606797749979

  Round方法遇到以.5结尾的梳子转换为整数时将舍入为最近的偶数位。 

八:随机数

Random类用于生成随机数。默认情况下,Random类的无参构造函数使用系统时钟生成其种子值,而参数化构造函数可根据当前时间的刻度数采用Int32值。注意:由于时钟分辨率有限,频繁的创建不同的Random对象会创建出产生相同随机数序列的随机数生成器。编程时,不要重复创建Random实例来生成随机数,避免产生相同随机数的结果

如下代码为随机生成10个随机数赋值给int型数组:

int[] num = new int[10];

Random r = new Random();

for(int i=0;i<num.length;i++)

{

  num[i] = r.Next(101);//返回小于101的非负随机数

}


posted on 2012-03-02 00:40  +Hansen+  阅读(646)  评论(0)    收藏  举报

导航