C# DateTime各种常用操作

时间转换也是我们开发中常用的,例如:获取当前系统时间、获取UTC时间、日期时间格式化、0时区转换成当前系统时区、日期时间运算、取单个日期时间;

一、获取日期时间


//获取当前系统时间
var currentTime = DateTime.Now;
//获取UTC时间
var utc = DateTime.UtcNow;

二、日期时间格式化

//获取当前系统时间
var currentTime = DateTime.Now;
Console.WriteLine(currentTime.ToString("yyyy/MM/dd HH:mm:ss"));
Console.WriteLine(currentTime.ToString("yyyy/MM/dd"));
Console.WriteLine(currentTime.ToString("HH:mm:ss"));

三、时区日期时间转换

//获取UTC时间
var utc1 = DateTime.UtcNow;
//将UTC时间转换成当前系统时区
var currentDateTime = timeZone.ToLocalTime(utc1);
//将当前系统时间转换成UTC时间
var utc2 = timeZone.ToUniversalTime(currentDateTime);
Console.WriteLine("UTC日期时间:{0}",utc1);
Console.WriteLine("将UTC时间转换成当前系统时区的日期时间:{0}",currentDateTime);
Console.WriteLine("将当前系统时间转换成UTC时间的日期时间:{0}", utc2);

四、取单个日期时间

//获取当前系统时间
var currentDateTime = DateTime.Now;
//年
Console.WriteLine("年:" + currentDateTime.Year);
//月
Console.WriteLine("月:" + currentDateTime.Month);
//日
Console.WriteLine("日:" + currentDateTime.Day);
//小时
Console.WriteLine("小时:" + currentDateTime.Hour);
//分钟
Console.WriteLine("分钟:" + currentDateTime.Minute);
//秒
Console.WriteLine("秒:" + currentDateTime.Second);
//毫秒
Console.WriteLine("毫秒:" + currentDateTime.Millisecond);

五、日期时间运算

//获取当前系统时间
var currentDateTime = DateTime.Now;
//加年
Console.WriteLine("加年:" + currentDateTime.AddYears(1));
//加月
Console.WriteLine("加月:" + currentDateTime.AddMonths(1));
//加日
Console.WriteLine("加日:" + currentDateTime.AddDays(1));
//加小时
Console.WriteLine("加小时:" + currentDateTime.AddHours(1));
//加分钟
Console.WriteLine("加分钟:" + currentDateTime.AddMinutes(1));
//加秒
Console.WriteLine("加秒:" + currentDateTime.AddSeconds(1));
//加毫秒
Console.WriteLine("加毫秒:" + currentDateTime.AddMilliseconds(1));

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值