-2

I am reading an input from a device on a comm port, that is a date in the following format "dd/MM/yyyy hh:mm" to a string value. I am trying to format the date to show "ddMMyyyy hh:mm:ss". I have tried the following but get the error below code:

(input value is "31/08/2018 02:32")

        public string ParseLine(string Line)
        {
            var input = Line.Split(',');
            var dateTime = DateTime.Parse (input[0]);
            var Action = input[1] == "1" ? "ONL" : "OFL";
            var readerAddr = input[1] == "1" ? "S" : "T";
            var TagType = input[2];
            var TagNum = input[3].Substring(TagType.Length);

            return $"{Action},{TagNum},{readerAddr},{dateTime:ddMMyyyy hh:mm:ss}";
        }

Any advise will be appreciated?

3 Answers3

1

Use DateTime.TryParseExact to check if 'input[0]' has a valid datetime value. Example:

public string ParseLine(string Line)
{
   ...
   if(!DateTime.TryParseExact(input[0], "ddMMyyyy hh:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.None, out var result))
     {
         //Is not a valid date :C
     }

   Console.WriteLine("Valid date: " + result);
}
Adolfok3
  • 304
  • 3
  • 14
0

In case date time would be in some weird format, you will need to use DateTime.ParseExact(..) method like this:

var dateTime = DateTime.ParseExact(input[0], "dd/MM/yyyy hh:mm");

However, your format is one of the accepted ISO formats, so it should work like you wrote down. The best reason why is does not work is that the value of input[0] is not what you expect, so at first check what this variable actually contains.

Dmitry Korolev
  • 675
  • 4
  • 20
0

Thanks to everyone's comments and advise I managed to get it right by using these two methods:

var dateTime = DateTime.ParseExact(input[0], "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);

and

return $"{Action},{TagNum},{readerAddr},{dateTime:ddMMyyyy HH:mm:ss}";