C # DateTime various conventional operations

We developed the conversion time is commonly used, for example: obtaining the current system time, obtaining UTC time, date and time format, converted into a time zone 0, the current system zone, time of operation, take a single date and time;

First, access date and time


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

Second, the date and time format

//获取当前系统时间
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"));

Third, the time zone conversion date

//获取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);

Fourth, the date and time to take a single

//获取当前系统时间
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);

Fifth, the date and time of operation

//获取当前系统时间
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));

 

Published 21 original articles · won praise 0 · Views 601

Guess you like

Origin blog.csdn.net/Stodger0216/article/details/103695509