How to concatenate 2 string datetime values

Viewed 47

How to concatenate 2 string datetime values in C# ? I have these 2 variables as shown below :

string a = "03-10-2022 15:20";  --> this is the datetime value
string b = "10024.45";          --> this is just milliseconds
string c = a + ":" + b;         --> this is concatenating 2 variables to get a
                                    DateTime value with milliseconds.

Now the value of c is

c = "03-10-2022 15:20:10024.45"

I want to create (NOT Convert) a new DateTime value (with millisecond) from the variable c ? Something like

DateTime dt = new DateTime(c); 
       

Don't use any datetime functions. I just want to "Concatenate" datetime var and millisecond var and create a new Datetime values with milliseconds from it.

This is for plotting the X axis of a chart. The x axis values will be like :

03-10-2022 15:20:10024.45, 
03-10-2022 15:25:11324.25,
03-10-2022 15:35:678.35, etc

Please help me to create a new datetime value with millisecond from a string ???

When I tried like this, it threw error saying that invalid data format - DateTime.

DateTime dt = DateTime.Parse(c); // error saying invalid 
                                 // data format : DateTime.
       
1 Answers

If you want to obtain DateTime (or its representation) from a and b you can parse, add millseconds and finally format into the desired representation:

string a = "03-10-2022 15:20";
string b = "10024.45";

// "03-10-2022 15:20:10.02"
// if you want DateTime, not string remove the last `.ToString(...)`
var result = DateTime
  .ParseExact(a, "d-M-yyyy H:m", CultureInfo.InvariantCulture)
  .AddMilliseconds(double.Parse(b, CultureInfo.InvariantCulture))
  .ToString("dd-MM-yyyy HH:mm:ss.ff");

If you have combination of date and milliseconds c, you can split it back into initial parts (datetime and milliseconds to add) then parse and add milliseconds:

// Note that we have two parts:
// Date and Time: 03-10-2022 15:20
// Milliseconds:  10024.45 
string c = "03-10-2022 15:20:10024.45";

int p = c.LastIndexOf(':');

DateTime result = DateTime
  .ParseExact(c.Substring(0, p), "d-M-yyyy H:m", CultureInfo.InvariantCulture)
  .AddMilliseconds(double.Parse(c.Substring(p + 1), CultureInfo.InvariantCulture));
Related