'Is there a way to get milliseconds to show when I call .ToString() on a DateTime WITHOUT using "fff"?
I am pulling a DateTime value from a database that I need to store in a textbox (it's an ASP.NET TextBox if you must know). This DateTime contains milliseconds. I then need to save this value back to the database.
The problem: When I do MyTextBox.Text = dbValue.ToString(), the milliseconds are excluded. When the user goes to save the record, it does a DateTime.Parse() on the TextBox value and writes that back to the database. Since the string no longer contains milliseconds, that component of the DateTime is lost on the save.
I am aware that I could specify the milliseconds on the way in by providing a custom format string that uses fff, but I am sort of wanting this to be considerate of culture. This means I don't want to hardcode a format string since that format string could theoretically be invalid if my code is executed on a machine using different culture info.
Conceptually, I am looking for a dynamic approach where all I have to do is tell .ToString() to use milliseconds based on the current culture without having to provide a format string.
Solution 1:[1]
I will Suggest to use a extension methods for that ...
public static class Extended
{
public static String ToDateX(this DateTime Caller)
{
return Caller.ToString("dd-MMM-yyyy HH-mm-ss-fff", new System.Globalization.CultureInfo("en-gb"));
}
}
This may resolved your problem since it will not use application Culture ..
Solution 2:[2]
I know @oscilatingcretin your requirement might be fulfilled in these days .. but for sake of fresh programmer who are facing these type problems.. i am posting an answer .. which is fully independent of Culture
private static void Main(string[] args)
{
//Cloning culture to assign
var newCulture = System.Threading.Thread.CurrentThread.CurrentCulture.Clone() as CultureInfo;
//Datetime.ToString() internally use
//Datetime.ToString(DateTimeFormat.ShortDatePattern+" "+ DateTimeFormat.LongTimePattern)
newCulture.DateTimeFormat.LongTimePattern = "hh:mm:ss fff";
//you can specify custom format for month tooo
//newCulture.DateTimeFormat.ShortDatePattern = "dd-MMM-yy";
System.Threading.Thread.CurrentThread.CurrentCulture = newCulture;
DateTime d = DateTime.Now;
Console.WriteLine(d.ToString());
Console.ReadKey();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Moumit |
| Solution 2 | Moumit |
