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!

Tuesday, June 5, 2007

Asp.Net & Formatting XML string – code snippet

A simple code snippet to show how to format XML string with proper indentation:


public static string FormatXml(string unformattedXML)
{
XmlDocument xd = new XmlDocument();
xd.LoadXml(unformattedXML);
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (XmlTextWriter xtw = new XmlTextWriter(sw))
{
xtw.Formatting = Formatting.Indented;
xd.WriteTo(xtw);
}
}
return sb.ToString();
}

Love coding!