简体   繁体   中英

C# Date in CSV file

I have to change a csv file with several dates in it. Every row starts with a date followed whith data. 11-nov-2015,data,data,data 10-nov-2015,data,data,data 9-nov-2015,data,data,data

With the following code I put the data in the right place (20141109 (yyyymmdd))

string[] values = lines1[i].Split(',');

if (values.Length >= 3)
{
    string[] parts = values[0].Split('-');
    if (parts.Length == 3)
    {
        values[0] =  String.Format("{0}-{1}-{2}", parts[2], parts[1], parts[0]);
        lines1[i] = String.Join(",", values);
    }
}

But two problems remain: 1) The month has to change from nov to 11

2) In the file I download the day for example 9-nov-2014 has to change to 09. for 8-nov-2014 to 08. So an extra 0.

How can this be solved in C#

Instead of making your own datetime format parser, you should use the one already available for you. DateTime.TryParseExact is your tool to convert a string in a date when you know the exact format.
Converting back the date, in the string format that you like, is another task easily solved by the override of ToString() specific for a datetime

string[] values = lines1[i].Split(',');
if (values.Length >= 3)
{
    DateTime dt;
    if (DateTime.TryParseExact(values[0], "d-MMM-yyyy", 
        System.Globalization.CultureInfo.CurrentCulture, 
        System.Globalization.DateTimeStyles.None, out dt))
    {
        values[0] = dt.ToString("yyyyMMdd");
        lines1[i] = String.Join(",", values);
    }
}

I would parse the string into a date and then write it back using a custom date format. From this link we can write this code:

String pattern = "dd-MMM-yyyy";
DateTime dt;
if (DateTime.TryParseExact(values[0], pattern, CultureInfo.InvariantCulture, 
                           DateTimeStyles.None,
                           out dt)) {
    // dt is the parsed value
    String sdt = dt.ToString("yyyyMMdd"); // <<--this is the string you want
} else {
    // Invalid string, handle it as you see fit
}

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