1 Convert类
Convert类位于System名称空间下,用于将一个值类型转换到另一个值类型。
【例】使用Convert类
using System;
class Test
{
public static void Main()
{
double d1=23.5D,d2=23.4D;
int i1=Convert.ToInt32(d1);
int i2=Convert.ToInt32(d2);
Console.WriteLine("{0},{1}",i1,i2);
int i=0;
bool b1=Convert.ToBoolean(d1);
bool b2=Convert.ToBoolean(i);
Console.WriteLine("{0},{1}",b1,b2);
string s="123";
i=Convert.ToInt32(s);
Console.WriteLine("{0},{1}",s,i);
}
}
输出结果为:
24,23
True,False
123,123
2 DateTime类
dateTime类可以表示范围在0001年1月1日午夜12:00:00~9999年12月31日晚上11:59:59之间的日期和时间,最小事件单位为100ns。
TimeSpan类可以表示一个时间间隔。其范围在Int64.MinValue~Int64.MaxValue之间。
【例】使用DateTime类
using System;
class Test
{
public static Main()
{
DateTime dt1=new System.DateTime
(
2016, //Year
12, //Month
31, //Day
22, //Hour
35, //Minute
5, //Second
15 //Millisecond
);
DateTime dt2=new DateTime(2017,3,05);
Console.WriteLine("{0:F}--{1}",dt1,dt2);
dt1=DateTime.Now;
int i=dt1.Day; //当月的第几天
int j=dt1.Month; //月
int k=dt.Year; //年
Console.WriteLine("{0}--{1}--{2}--{3}",dt1,i,j,k);
DateTime t1=dt1.Date; //日期部分
k=dt1.Hour; //小时
Console.WriteLine("{0}--{1}",dt1,k);
TimeSpan ts1=dt1.TimeOfDay; //当天的时间
TimeSpan ts2=dt1-dt2;
i=ts2.Days;
Console.WriteLine("{0}--{1}--{2}",ts1,ts2,i);
string s1=dt1.ToLongDateString();
string s2=dt1.ToShortDateString();
string s3=string.Format("{0:yyyy.MM.dd}",dt1); //注意:M为月,m为分钟
Console.WriteLine("{0}--{1}--{2}--{3}",dt1,s1,s2,s3);
}
}
输出结果为:
2016年12月31日 22:35:05--2017-3-5 0:00:00
2017-3-23 21:38:34--23--3--2017
2017-3-23 21:38:34--21
21:38:34.1482832--611.21:38:34.1482832--611
2017-3-23 21:38:34--2017年3月23日--2017-3-23--2017.03.23
在浏览网页时,经常会见到显示当前日期、时间、星期的信息,下面用控制台应用程序说明完成这个功能的方法。
【例】显示当前日期和时间
using System;
public class Test
{
public static void Main()
{
string[] weekDays={"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
DateTime now=DateTime.now;
string str=string.Format("{0:现在是yyyy年M月d日,H点m分},{1}",now,weekDays[(int)now.DayOfWeek]);
Console.WriteLine(str);
DateTime start=new DateTime(2017,1,1);
TimeSpan times=now-start;
Console.WriteLine("从2017年1月1日起到现在已经过了{0}天",times.Days);
}
}
3 Math类
Math类位于System名称空间下,为三角函数、对数函数和其他通用数学函数提供常数和静态方法。
【例】使用Math类
using System;
public class Test
{
public static void Main()
{
int i=10,j=-5;
double x=1.3,y=2.7;
double a=2.0,b=5.0;
Console.WriteLine(string.Format("-5的绝对值为{0}",Math.Abs(j)));
Console.WriteLine(string.Format("大于等于1.3的最小整数位{0}",Math.Ceiling(x)));
Console.WriteLine(string.Format("小于等于2.7的最大整数为{0}",Math.Floor(y)));
Console.WriteLine(string.Format("10和-5的较大者为{0}",Math.Max(i,j)));
Console.WriteLine(string.Format("1.3和2.7的较小者为{0}",Math.Min(x,y)));
Console.WriteLine(string.Format("2的5次方为{0}",Math.Pow(a,b)));
Console.WriteLine(string.Format("1.3的四舍五入值为{0}",Math.Round(x)));
Console.WriteLine(string.Format("5的平方根为{0}",Math.Sqrt(b)));
}
}
输出结果为:
-5的绝对值为5
大于等于1.3的最小整数位2
小于等于2.7的最大整数为2
10和-5的较大者为10
1.3和2.7的较小者为1.3
2的5次方为32
1.3的四舍五入值为1
5的平方根为2.23603797749979