简体   繁体   中英

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.

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 .

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 ?

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.

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:

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.

  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. 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. Here is a code example that can be run in 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. I can then use the same custom format specifier options to represent that DateTime instance however I want. From here it would be easy to add another TextBox which uses the same DateTime instance but shows the month in text for example.

When all of this comes together this will be your result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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