Optimal DateTime Converter for all cultures
I am about to create a Converter to translate the date into a custom format.
In fact in one converter I have a date like this 17/05/2011 00:00:00 that I would like to convert to simply 17/05/2011. However the culture shall be also taken into consideration.
In my example above I had the British culture, but if the user is American then it shall be converted into 05/17/2011.
Effectively I would also need a ConvertBack to convert the date back regardless of the culture into a Database friendly format to save it back universally and safe without misunderstanding.
This was my first try which already fails:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if(value == null)
return null;
DateTime date = DateTime.Parse(value.ToString(), culture);
return date;
}
Also surprising is that the CultureInfo parameter above is Us-en, despite everything in Windows is set to United Kingdom. Btw I am using this converter for Silverlight 4, perhaps obtaining the culture is different here... None the less 开发者_StackOverflow中文版weird enough I get an expection 'String was not recognized as a valid DateTime.' I think this is due the American culture I have there that doesn't understand 17 as a month. How do I set my local culture in a silverlight app?
And then I would need a second converter to return only the time similar to above. i figured I might be able to use the overload DateTimeStyles.NoCurrentDateDefault for it to generate only time from dates, correct?
Many Thanks for your help,
Setting a culture can be done on the current thread, each thread in an application can be in a different culture.
http://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture(v=VS.100).aspx
Curious, if your computer is in en-gb but your application is in en-us, I would surmise the application is being put into that culture explicitly, perhaps by the configuration file. If the application is not given a culture, it takes the OS culture.
In ASP.NET web apps I remember you could also specify culture in the config file.
Is your end goal just to cut off the time portion of the DateTime
? If so, there is a DateTime.Date
property available and you could then convert using the default .NET culture support.
The ConvertBack
method could save the time as UTC, there are various methods on a DateTime
for saving to UTC. UTC includes time zone information and comes in one format, good for databases.
http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx
Though to be honest, if SQL Server is your database server, so long as you store dates as dates and not strings, again culture is taken care of for you.
精彩评论