简体   繁体   English

将 dd.mm.yyyy 转换为 c# 中 .csv 文件中的 yyyy-mm-dd

[英]convert dd.mm.yyyy to yyyy-mm-dd in .csv file in c#

I have a CSV file like this:我有一个像这样的 CSV 文件:

abc;30.11.2021;xyz

I need to convert the date value to this format:我需要将日期值转换为这种格式:

abc;2021-11-30;xyz

any ideas for that?有什么想法吗?

Currenty I do this:目前我这样做:

//config Ini auslesen für Quell- und Zieldatei
        var dic = File.ReadAllLines("config.ini")
          .Select(l => l.Split(new[] { '=' }))
          .ToDictionary(s => s[0].Trim(), s => s[1].Trim());
        //Wert für Quelle
        string source = dic["source"];
        //Wert für das Ziel
        string target = dic["target"];

        string filePath = source ;

        var csv = File
        .ReadLines(source)
        .Select((line, index) => index == 0
           ? line + ";ExtID"                                     // Neue Kopfzeile
           : line + ";" + string.Concat(line.Split(';').Take(2)) // Spalte 1 + 2 in neue Spalte einfügen
         )
        .ToList();

        File.WriteAllLines(target, csv);

So I read an csv file, add a column and fill this column but to be honnest I don't know how to convert the date value.所以我读了一个 csv 文件,添加一列并填充这一列,但老实说,我不知道如何转换日期值。

use ParseExact to convert the string to DateTime and use ToString to convert back to the desired format使用ParseExact将字符串转换为DateTime并使用ToString转换回所需的格式

var s = DateTime.ParseExact("30.11.2021", "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
Console.WriteLine(s);

Something like this:像这样的东西:

using (System.IO.StreamWriter writer = new System.IO.StreamWriter("newfile.csv"))
 {
     foreach (string line in System.IO.File.ReadAllLines("oldfile.csv"))
     {
         string[] items = line.Split(new[] { ';' });

         string newDateFormat = DateTime.ParseExact(items[1], "dd.MM.yy", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy-MM-dd");

         writer.Write(items[0]);
         writer.Write(';');
         writer.Write(newDateFormat);
         writer.Write(';');
         writer.Write(items[2]);
         writer.Write(';');
         writer.WriteLine();
     }
 }

Replace "oldfile.csv" with the input file and the output will be saved to "newfile.csv".用输入文件替换“oldfile.csv”,输出将保存到“newfile.csv”。

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

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