Reputation: 9
I am developing WinForm application on .NET 2.0 and SQL Server Express 2005.
I am facing a problem with datetime conversion.
1) I need to display datetime(datetimepicker) on UI like "dd/MM/yyyy" so I am using
public static void ChangeDateFormat(DateTimePicker dtp)
{
dtp.Format = DateTimePickerFormat.Custom;
dtp.CustomFormat = "dd/MM/yyyy";
}
2) For inserting data to SQL Server I am using
datetimePicker1.ToShortDateString()
3) Getting data from SQL Server
Convert(varchar(10),dt,103)
4) Assign string date "31/03/2013" to datetimepiker
public static DateTime StringToDate(string value)
{
IFormatProvider formatProvider = new CultureInfo("en-GB");
DateTime dt = DateTime.Parse(value, formatProvider);
return dt;
}
5) Assign SQL date to datetimepicker
Select dt from ams
datetimepicker1.value=DateTimeClass.dbDateTime( dt );
public static DateTime dbDateTime(string value)
{
IFormatProvider formatProvider = new CultureInfo("en-US");
DateTime dt = DateTime.Parse(value, formatProvider);
return dt;
}
Problem : if a user changed region or date format of Windows, an error occurs.
I am pretty confused. I need to make my application region independent.
Upvotes: 0
Views: 531
Reputation: 27944
The problem is not that you want to convert a string from sql into a DataTime value, but that you save the DateTime as a string in sql server. By saving your value as a Date, you do not have to convert and have no problems with regions, etc. The solution should be changing your sql column to a date type instead of trying to convert dates from which you have to guess the formatting.
Upvotes: 2