using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections.Generic;
using System.Text;
namespace Bowin.Common.Utility
{
public static class DateHelper
{
public static DateTime GetYearMonthStartDate(int yearMonth)
{
return DateTime.ParseExact(yearMonth.ToString() + "01", "yyyyMMdd", null);
}
public static string FormatYearMonth(int yearMonth, string formatString)
{
return GetYearMonthStartDate(yearMonth).ToString(formatString);
}
public static bool IsYearMonthBetween(int yearMonth, int fromMonth, int toMonth)
{
var yearMonthDate = GetYearMonthStartDate(yearMonth);
var fromDate = new DateTime(DateTime.Today.Year, fromMonth, 1);
DateTime toDate;
if (toMonth >= fromMonth)
{
toDate = new DateTime(DateTime.Today.Year, toMonth, 1);
}
else
{
toDate = new DateTime(DateTime.Today.Year + 1, toMonth, 1);
}
return yearMonthDate >= fromDate && yearMonthDate <= toDate;
}
public static double GetYearSpan(DateTime fromDate, DateTime toDate)
{
double yearSpanBase = toDate.Year - fromDate.Year;
double toDateYearDays = DateTime.IsLeapYear(toDate.Year) ? 366 : 365;
DateTime toYearBase;
if (fromDate.Month == 2 && fromDate.Day > DateTime.DaysInMonth(toDate.Year, 2))
{
toYearBase = new DateTime(toDate.Year, 2, DateTime.DaysInMonth(toDate.Year, 2));
}
else
{
toYearBase = new DateTime(toDate.Year, fromDate.Month, fromDate.Day);
}
return yearSpanBase + (toDate.Subtract(toYearBase).TotalDays / toDateYearDays);
}
public static int YearMonthAdd(int yearMonth, int addMonths)
{
return GetYearMonthStartDate(yearMonth).AddMonths(addMonths).ToYearMonth();
}
public static int? YearMonthAdd(int? yearMonth, int addMonths)
{
if (yearMonth.HasValue)
{
return YearMonthAdd(yearMonth.Value, addMonths);
}
else
{
return null;
}
}
public static int ToYearMonth(this DateTime dateTime)
{
return dateTime.Year * 100 + dateTime.Month;
}
///
/// 计算两个时间相差的月数
///
///
///
///
public static int DiffMonth(DateTime statrDate, DateTime endDate)
{
return (endDate.Year * 12 + endDate.Month - statrDate.Year * 12 - statrDate.Month);
}
}
}