用户登录
用户注册

分享至

C# 常用日期时间函数(老用不熟)

  • 作者: 半萌半骚长发及腰
  • 来源: 51数据库
  • 2021-10-19
--datetime 数字型
system.datetime currenttime=new system.datetime();
1.1 取当前年月日时分秒
currenttime=system.datetime.now;
1.2 取当前年
int 年=currenttime.year;
1.3 取当前月
int 月=currenttime.month;
1.4 取当前日
int 日=currenttime.day;
1.5 取当前时
int 时=currenttime.hour;
1.6 取当前分
int 分=currenttime.minute;
1.7 取当前秒
int 秒=currenttime.second;
1.8 取当前毫秒
int 毫秒=currenttime.millisecond;
(变量可用中文)
1.9 取中文日期显示——年月日时分
string stry=currenttime.tostring("f"); //不显示秒
1.10 取中文日期显示_年月
string strym=currenttime.tostring("y");
1.11 取中文日期显示_月日
string strmd=currenttime.tostring("m");
1.12 取当前年月日,格式为:2003-9-23
string strymd=currenttime.tostring("d");
1.13 取当前时分,格式为:14:24
string 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();//最后一天
软件
前端设计
程序设计
Java相关