简体   繁体   中英

Parse string in the right Format to DateTime

I have the problem, that i can't parse my string in the right format to DateTime. I tried a lot of different ways and searched on several websites, but i didn't find a solution for my problem

string vonDatum = dtpVon.Value.ToString("dd.MM.yyyy");
        DateTime startDatum = DateTime.ParseExact(vonDatum, "dd.MM.yyyy", null);
        String bisDatum = dptBis.Value.ToString("dd.MM.yyyy");
        DateTime endDatum = DateTime.ParseExact(bisDatum, "dd.MM.yyyy", null);

As you can see, i want to parse in as dd.MM.yyyy. But i receive something like dd.MM.yyyy.ss.fff (not sure about the ss.fff, but I get also the seconds and the milliseconds back).

Thanks a lot if someone can help me

parsing datetime into specific string format or converting it into specific culture usually throw exception. You can use the following code to get this format dd.MM.yyyy

DateTime dateString = DateTime.Now;

string day = dateString.Day.ToString();
string month = dateString.Month.ToString();
string year = dateString.Year.ToString();

string date = day + "." + month + "." + year;
Console.WriteLine(date);

output : 10.2.2017

I just found it out by myself. If anyone have the same problem, here is how you can handle it.

 string datum = String.Format("{0:dd/MM/yyyy}", date);

By example, I'm using it in this context.

string vonDatum = dtpVon.Value.ToString("dd.MM.yyyy");
        DateTime startDatum = DateTime.ParseExact(vonDatum, "dd.MM.yyyy", null);

        string bisDatum = dptBis.Value.ToString("dd.MM.yyyy");
        DateTime endDatum = DateTime.ParseExact(bisDatum, "dd.MM.yyyy", null);

 for (DateTime date = startDatum; date <= endDatum; date = date.AddDays(1))
            {
                string datum = String.Format("{0:dd/MM/yyyy}", date);
                // Erste tabellenbefüllung erstellen 
                sqlite_cmd.CommandText = "INSERT INTO einteilung (mitarbeiter, arbeitsschicht, datum) VALUES ('"+mitarbeiter+"', '"+arbeitsschicht+"', '"+datum +"');";
                sqlite_cmd.ExecuteNonQuery();
            }

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