C# winform DateTime

最近用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;
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值