Unity DateTime 相关
当前时间
//dateTime = DateTime.UtcNow;//中时区当前时间
dateTime = DateTime.Now;
int year = dateTime.Year;
int month = dateTime.Month;
int day = dateTime.Day;
int hour = dateTime.Hour;
int minute = dateTime.Minute;
int second = dateTime.Second;
int millisecond = dateTime.Millisecond;
long ticks = dateTime.Ticks;
DateTime date = DateTime.Now.Date;
DayOfWeek dayOfWeek = dateTime.DayOfWeek;
dateTime = DateTime.Today;//与DateTime.Now.Date相同
时间增加(减少)
dateTime = dateTime.AddYears(13);
dateTime = dateTime.AddMonths(13);
dateTime = dateTime.AddDays(13);
dateTime = dateTime.AddHours(13);
dateTime = dateTime.AddMinutes(13);
dateTime = dateTime.AddSeconds(13);
dateTime = dateTime.AddMilliseconds(13);
dateTime = dateTime.AddTicks(13);
数值为负时减少。
时间差
TimeSpan timeSpan = DateTime.Today.AddDays(13) - DateTime.Now;
int day = timeSpan.Days;
int hour = timeSpan.Hours;
int minute = timeSpan.Minutes;
int second = timeSpan.Seconds;
int millisecond = timeSpan.Milliseconds;
long ticks = timeSpan.Ticks;
double totalDays= timeSpan.TotalDays;
double totalHours = timeSpan.TotalHours;
double totalMinutes = timeSpan.TotalMinutes;
double totalSeconds = timeSpan.TotalSeconds;
double totalMilliseconds = timeSpan.TotalMilliseconds;
DateTime 转换成字符串
dateTime = new DateTime(1989, 12, 13, 05, 03, 13);
dateTimeStr = dateTime.ToString();
dateTimeStr = dateTime.ToString("G");
dateTimeStr = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
字符串转换成DateTime
dateTime = Convert.ToDateTime(dateTimeStr);
或
DateTime.TryParse(dateTimeStr, out dateTime);
比较
compareTo = DateTime.Compare(dateTime1, dateTime2);
或
compareTo = dateTime1.CompareTo(dateTime2);
compareTo 为-1时,dateTime1 更久远;compareTo 为1时,dateTime2 更久远;compareTo 为0时,dateTime1 和dateTime2 相等。