1

So I have string that is 24.08.2010. 21:21:21, I want to convert it to 2010-08-24 21:21:21 to be able to save it in the db.

I tried this

var input = "22.08.2010. 7:00:00";
var date = DateTime.ParseExact(input,"yy-MM-dd HH:mm:ss.fff", null);
Console.WriteLine(date);

but I get error:

System.FormatException: String was not recognized as a valid DateTime.

Anyone have idea how to convert this?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • 10
    Well your input is not the same as your format... so fix that – maccettura Nov 25 '19 at 16:29
  • You said `So I have string that is 24.08.2010. 21:21:21` but your code has `22.08.2010. 7:00:00`? o.O Also you _really_ have `.` after your year part? That's odd. _Just_ based your input, the right format seems as `dd.MM.yyyy. h:mm:ss`. Also it would be better to use _specific_ `CultureInfo` when you parse your strings to DateTime objects to prevent ambiguous situations. – Soner Gönül Nov 25 '19 at 16:31
  • 3
    Also, you should be saving your dates as the `Date` type in your DB, _never_ save a date as a string – maccettura Nov 25 '19 at 16:33
  • You need to parse the string using the format the string is currently in, then format the DateTime in the format you want it in. – Heretic Monkey Nov 25 '19 at 16:33
  • Your format string is not right is it? You have `yy` as the first part of the string. The first part is 22 which is a day. – Andrew Truckle Nov 25 '19 at 16:33
  • They are all listed here: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings The inout format string must match the content of the literal text, else the parser will decode it into the wrong chunks and won't be able to construct a date object. – Andrew Truckle Nov 25 '19 at 16:36
  • My mistake, but yes i have . after year part, my string format is dd.mm.yyy. HH:mm:ss and that is my input that i can't change, but also i can't save it in ms sql server database . –  Nov 25 '19 at 16:36
  • Parse exact expect to have the Exact format. This part is important so they added it to the function name. You gave `"yy-MM-dd HH:mm:ss.fff"`.. Is the input date starting with year on 2 digit? Followed by a `"-"`? Yeah you get a format Exception. That pretty self explanatory. – Drag and Drop Nov 25 '19 at 16:43

1 Answers1

2

First, you need to convert string input into date:

var input = "22.08.2010. 7:00:00";
var date = DateTime.ParseExact(input, "dd.MM.yyyy. H:mm:ss", null);

And than convert date to string:

Console.WriteLine(date.ToString("yy-MM-dd HH:mm:ss"));
Vano Maisuradze
  • 5,829
  • 6
  • 45
  • 73