简体   繁体   English

使用C#中的函数格式化日期和时间

[英]Formatting Date and Time with a function in C#

So I am getting the driver date from graphic card and display it into a TextBox but the value comes like this 20161216000000.000000-000 and I want to convert it into a real date. 所以我从显卡获取驱动程序日期并将其显示到TextBox但值如此20161216000000.000000-000 ,我想将其转换为实际日期。

I already got a function to convert this kind of dates, but it this case does does not work and after using it shows me like this 01-01-0001 00:00:00 . 我已经有一个函数来转换这种日期,但这种情况不起作用,使用后它显示我喜欢这个01-01-0001 00:00:00

This is my function code: 这是我的功能代码:

private static string FormatDateTime(object ObjInstallDate)
{
    object FinalDate = DBNull.Value;
    string strDate = Convert.ToString(ObjInstallDate);
    DateTime dtm;
    DateTime.TryParseExact(strDate, new string[] { "yyyyMMdd", "yyyy-MM-dd", "dd-MM-yyyy" },
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out dtm);
    if (!String.IsNullOrEmpty(strDate))
    {
        FinalDate = dtm;
    }
    return FinalDate.ToString();
}

Do you have any idea how I can get in this case 20161216000000.000000-000 something like 2016-12-16 ? 你知道我怎么能在这个案例20161216000000.000000-000这样的2016-12-16

Taking a substring does the job (if the format is always like shown): 获取子字符串可以完成工作(如果格式总是如图所示):

DateTime.TryParseExact(strDate.Substring(0, 8), "yyyyMMdd",
    System.Globalization.CultureInfo.InvariantCulture,
    System.Globalization.DateTimeStyles.None, out DateTime dtm);

To get the required format to present the result you can use 要获得所需的格式以显示您可以使用的结果

dtm.ToString("yyyy-MM-dd");

After looking at your code and question it looks like the date you are passing to the function is not in correct/expected format that c# supports, that's why it is giving you the default system's beginnning date which is 01-01-0001 00:00:00 here. 在查看您的代码和问题之后,看起来您传递给函数的日期不是c#支持的正确/预期格式,这就是它为您提供默认系统的开始日期01-01-0001 00:00的原因这里00

But, as a workl around, as I can observe first 8 digit of the input value is date part, so you can use that in following way: 但是,作为一个工作,我可以观察到输入值的前8位是日期部分,所以你可以按照以下方式使用它:

DateTime.TryParseExact(strDate.Substring(0, 8), "yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtm);

return dtm.ToString("yyyy-MM-dd");

You only needed to make sure your format matched your input, which none of your provided input formats did. 您只需要确保您的格式符合您的输入,而您提供的输入格式都没有。

See how the custom dateformat specifiers and literal characters line-up with your input. 查看自定义dateformat说明符和文字字符与输入的对齐方式

  Your input: 20161216000000.000000-000 format specifiers: yyyyMMddhhmmss.ffffff-000 

Bringing that format to your method you'll get this: 将这种格式带到您的方法,你会得到这个:

// takes an object, returns a DateTime or null in case of failure
DateTime FormatDateTime(object ObjInstallDate)
{
    DateTime dtm;
    if (!DateTime.TryParseExact(
        (string) ObjInstallDate, // notice that we don't hassle with the input here, 
                                 // only cast to a string
                                 // we simply rely on the parser of DateTimer.TryParseExact
        "yyyyMMddhhmmss.ffffff-000",  // this matches the format
                                      // if the -000 represents a timezone
                                      // you can use z00 or zz0 
                                      // don't use zzz as that expects -0:00
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, 
        out dtm)) 
    {
        // an invalid date was supplied, maybe throw, at least log
        Console.WriteLine("{0} is not valid", ObjInstallDate);
    }
    // we either return here null or a valid date
    return dtm; // !! No ToString() here
}

I cherry picked the needed custom format value from Custom Date and Time Format Strings . 我从自定义日期和时间格式字符串中选择了所需的自定义格式值。

Notice that I simply return the DateTime instance that was created. 请注意,我只返回已创建的DateTime实例。 You'll see next why I do that. 你会看到我为什么这么做的原因。

As you want to display the DateTime on a Winform (I assume in a textbox, but an label will work as well) you can now simply Databind the DateTime instance to the textbox and let the databinding plumbing do the formatting. 因为你想在Winform上显示DateTime(我假设在文本框中,但标签也可以工作),你现在可以简单地将DateTime实例数据绑定到文本框,让数据绑定管道进行格式化。 Here is a code example that can be run in LinqPad: 这是一个可以在LinqPad中运行的代码示例:

// take a string and make a date of it
var str = "20161216000000.000000-000";
DateTime dtm = FormatDateTime(str);

// show it on a Databind TextBox
var f = new Form();
var txt = new TextBox();
txt.Width = 200;
// bind the Text property
txt.DataBindings.Add(
    "Text",  // property on the textbox
    dtm, // our DateTime object
    null, // use the DateTime instance, not a property
    true, // use formatting 
    DataSourceUpdateMode.OnValidation, 
    null, // value to indicate null
    "yyyy-MM-dd"); // our format
f.Controls.Add(txt);
f.Show();

I'm using the overload of Add on the DataBindingsCollection that takes an Format string. 我在DataBindingsCollection上使用Add的重载,它接受一个Format字符串。 I can then use the same custom format specifier options to represent that DateTime instance however I want. 然后,我可以使用相同的自定义格式说明符选项来表示我想要的DateTime实例。 From here it would be easy to add another TextBox which uses the same DateTime instance but shows the month in text for example. 从这里可以很容易地添加另一个TextBox,它使用相同的DateTime实例,但在文本中显示月份。

When all of this comes together this will be your result: 当所有这些结合在一起时,这将是您的结果:

winform显示2016-12-01作为日期的文本框

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM