Thursday, June 28, 2007

Few DateTime tips…

How to get first of the month?

(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)).ToShortDateString()


How to get last day of the month?

(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month))).ToShortDateString()


How to find age in years?

public static int Age(DateTime DOB)

{

int years = DateTime.Now.Year - DOB.Year;

if (DateTime.Now.Month <>

(DateTime.Now.Month == DOB.Month && DateTime.Now.Day < DOB.Day))

years--;

return years;

}


How to convert specific formatted string to DateTime?

public static DateTime ToDateTime(string DateTimeAsString, string formatString)

{

DateTime dtTemp;

DateTime.TryParseExact(DateTimeAsString,

formatString,

System.Globalization.DateTimeFormatInfo.InvariantInfo,

System.Globalization.DateTimeStyles.None, out dtTemp);

return dtTemp;

}


How to truncate hour from the DateTime

public static DateTime TruncToHour(DateTime timeToTrunc)

{

return DateTime.Parse(timeToTrunc.ToShortDateString() + " " + timeToTrunc.Hour + ":00:00");

}

Love coding!

No comments: