Error when concatenating string date values

Viewed 55

I am reading some values from a csv file. The first column of the csv is Datetime who values are like 03-10-2022 15:20, 03-10-2022 15:26, etc.

Another column named Seconds whose values are like 1200.34, 1234.23, etc

I am taking these values using csvHelper class and is as shown below :

    string d0 = csv.GetField<string>("DATETIME"); 
    string d5 = csv.GetField<string>("SECONDS");

I wanted a datetime value with milliseconds by combining these two strings such as

    DateTime dt = d0 + ":" + d5; // I want it like 03-10-2022 15:20:1200.34

What I tried is as

    string format = "MM/dd/yyyy HH:mm:ss.ff";
    DateTime dtValue = DateTime.ParseExact(dt, format, CultureInfo.InvariantCulture);

Here I am getting the error : System.FormatException: 'String was not recognized as a valid DateTime.' - dt

This is for plotting a graph in the chart. THe x axis is the datetime value with milliseconds as each tick. The value will be concatenate 2 date values with milliseconds such 03-10-2022 15:20:1200.34, 03-10-2022 15:20:1345.45, etc

I think with out using any date time function, the datetime value will be the concatenation of datetime and milliseconds.

Without use any datetime functions, I want to concatenate these 2 values like concatenating 2 string.

 string F = "03-10-2022 15:20";
 string S = "1200.34"
 string result = F + ":" + S; // 03-10-2022 15:20:1200.34

Then create a new datetime object from result like :

 DateTime d = new DateTime(result....);

so we get d whose value will be 03-10-2022 15:20:1200.34

Is this possible in C# ???

1 Answers

parse the first part to a DateTime, the second to a double and then use AddSeconds to melt them together

DateTime d0 = Convert.ToDateTime(csv.GetField<string>("DATETIME")); 
DateTime complete = d0.AddSeconds( Convert.ToDouble(csv.GetField<string>("SECONDS"), CultureInfo.InvariantCulture ));

Here is a working example. After the edition you get an extra 20 minutes.

Explanation of errors:

DateTime dt = d0 + ":" + d5;

  1. here you concatenate strings and expect that the result should be of type DateTime. This will not work. The result will be a string. You would need to parse it.

  2. 1200 is not a valid range for seconds which is [0:59]. This is one of the reasons you get a format error. The other reason is probably that the format that you use does simply not match.

values are like 03-10-2022 15:20

and you use "MM/dd/yyyy"

Related