The whole world is divided into different time zones and cultures. Every country has own style to display date and time format. Like, in USA the date has been displayed in “mm/dd/yyyy” format while in Great Britain and India the date has been displayed in “dd/mm/yyyy” format. In the web era, it’s always tough to provide culture oriented user interface. It is easy to display the date in specific format on page using ASP.net. Programmer can easily use .ToString(“dd/mm/yyyy”); to display the date into British format. But it’s not easy to store date into server with formatting.
Let’s take one scenario to understand this, I have a webpage which sense the user’s current time zone and display the date according to that. But the website is hosted on the USA based server. So the SQL Server for the Website will have the “mm/dd/yyyy” format. The SQL Server will expect the date in “mm/dd/yyyy” format. This can create problem when we provide such user interface which accept the date into “dd/mm/yyyy” format. We have to convert the date back into server’s date format before saving into database.
There is no any direct method to convert the date format with DateTime type. Probably Convert.ToDateTime() provide such facility with iFormatProvider interface. But, I really don’t know how to use that. So, I found one another work-around to convert the date in other format.
It’s very tricky to convert the date format from “dd/MM/yyyy” to “mm/dd/yyyy” in .Net 2.0. Below is function, using that programmer can convert any date in any format to the server’s date format.
public DateTime ConvertDate(string Date, string CurrentDateFormat)
{
try
{
return DateTime.ParseExact(Date, CurrentDateFormat, new CultureInfo(Thread.CurrentThread.CurrentCulture.Name));
}
catch
{
throw;
}
}
1 comment:
Wow, its great idea. It work great for me. Thanks for posting.
Post a Comment