Datetime Format issues are the main thing that comes with Asp.Net application because of the Hosting Environment. If you have configured your application to run with default format of (MM/dd/yyyy) this would work fine with default setting in Regional & Language settings. If the format is changed the whole application ends up with Date Format errors. To overcome this we have a option which can be used to host the application in any environment without worrying for Date Format especially with LAPTOPS
using System.Globalisation;
public DateTime GetDateValue(string sDate, bool IsLongDate)
{
DateTime dt;
if (IsLongDate)
dt = DateTime.ParseExact(sDate, CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString() + " " + CultureInfo.CurrentCulture.DateTimeFormat.LongTimePattern.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.NoCurrentDateDefault);
else
dt = DateTime.ParseExact(sDate, CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.NoCurrentDateDefault);
return dt;
}
public string GetDBDateValue(string sDate, bool IsLongDate)
{
DateTime dtDBDate;
DateTime dt = GetDateValue(sDate, IsLongDate);
if (!IsLongDate)
{
dtDBDate = new DateTime(dt.Year, dt.Month, dt.Day);
return dtDBDate.ToString("d", CultureInfo.CreateSpecificCulture("en-us"));
}
else
{
dtDBDate = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
return dtDBDate.ToString("G", CultureInfo.CreateSpecificCulture("en-us"));
}
}
In these the First Function is used to retrieve the Date as per the format specified in Regional Settings.
EX: string sDate = "22/03/2010";
Datetime dtFormatedDate = GetDateValue(sDate , true)
OUTPUT : [dtFormatedDate = 22/03/2010 12:00:00 a.m;] In a Datetime format even if the day comes first
This can be used anywhere in your source and the C# predicts the Day, Month and Year respectively.
But in case of SQL if you pass the same format that would throw an error of Invalid Date format. In such case use the Second function which just makes the DATE FORMAT appropriate to SQL Server format.
EX: string sDate = "22/03/2010";
string sFormatedDate = GetDBDateValue(sDate , false)
OUTPUT : [sFormatedDate = 03/22/2010;]
No comments:
Post a Comment