最近用DateTime感觉十分方便
//自动设定现在时间
DateTime now = new DateTime.Now;
//自己设时间
DateTime theTime = new DateTime(2019, 04, 18, 15, 57, 56);
//可以设置不同格式
DateTime theTime = new DateTime(2019, 04, 18);
DateTime theTime = new DateTime(2019, 04, 18, 12, 13, 14 ,445);
有10几种重载
// ticks:
// 以 100 纳秒为单位表示的日期和时间。
public DateTime(long ticks);
// kind:
// 枚举值之一,该值指示 ticks 是指定了本地时间、协调世界时 (UTC),还是两者皆未指定。
public DateTime(long ticks, DateTimeKind kind);
public DateTime(int year, int month, int day);
public DateTime(int year, int month, int day, Calendar calendar);
public DateTime(int year, int month, int day, int hour, int minute, int second);
public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind);
// calendar:
// 用于解释 year、month 和 day 的日历。
public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar);
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond);
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind);
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar);
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind);
但是设定text的时候也不用麻烦到改宣告
例如 你想设定 2019/04/19 的 9点钟
你就写了
DateTime theTime= new DateTime(2019, 04, 18, 09);
发现报错了
其实不用那么麻烦
你可以这样写
DateTime theTime = new DateTime(2019, 04, 18, 09,mm , ss);
the Time.ToString(yyyyMMddhh);
那如果你测试了
DateTime theTime = new DateTime(2019, 04, 18, 21,mm , ss);
the Time.ToString(yyyyMMddhh);
你会发现跟前一项输出一模一样
那是因为我们设定的小时是12小时制 不是24小时制
DateTime theTime = new DateTime(2019, 04, 18, 21,mm , ss);
//把hh改成大写HH (12小时 --> 24小时)
the Time.ToString(yyyyMMddHH);
就会显示正确了
而如果要昨天、明天 或是月、年呢?
//昨天
theTime.AddDays(-1);
//明天
theTime.AddDays(+1);
//上个月
theTime.AddMonths(-1);
//下个月
theTime.AddMonths(+1);
//明年
theTime.AddYears(+1);
如果你要获得这个DateTime的其中一项时间也是可以的
//年
theTime.Year;
//月
theTime.Month;
//日
theTime.Day;
//周几
theTime.DayOfWeek;
//一年中的第几天
theTime.DayOfYear;