4

我从需要存储在文本框中的数据库中提取 DateTime 值(如果您必须知道,它是 ASP.NET 文本框)。此 DateTime 包含毫秒。然后我需要将此值保存回数据库。

问题:当我这样做MyTextBox.Text = dbValue.ToString()时,毫秒被排除在外。当用户去保存记录时,它会对DateTime.Parse()TextBox 值执行一个操作并将其写回数据库。由于字符串不再包含毫秒,因此 DateTime 的该组件在保存时会丢失。

我知道我可以通过提供一个使用的自定义格式字符串来指定进入的毫秒数fff,但我有点希望这能考虑到文化。这意味着我不想硬编码格式字符串,因为如果我的代码在使用不同文化信息的机器上执行,该格式字符串理论上可能无效。

从概念上讲,我正在寻找一种动态方法,我所要做的就是告诉.ToString()根据当前文化使用毫秒,而不必提供格式字符串。

4

2 回答 2

1

我会建议为此使用扩展方法...

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"));
        }
    }

这可能会解决您的问题,因为它不会使用应用程序Culture ..

于 2013-11-11T14:26:39.387 回答
0

我知道@oscilatingcretin这些天你的要求可能会得到满足..但是为了面对这些类型问题的新程序员..我发布了一个答案..这是完全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();

    }
于 2016-03-09T13:58:36.820 回答