Answered Convert string data to datetime

AussieBoy

Well-known member
Joined
Sep 7, 2020
Messages
78
Programming Experience
Beginner
Hi, can I pass a string data into a datetime?

I have a string BufferDateTime containing 2020,07,22,16,11,38
C#:
dt = new DateTime(BufferDateTime);
Do I convert it to a long?
Thanks
 
You should use the other constructor instead:
C#:
public DateTime (int year, int month, int day, int hour, int minute, int second);
 
If you're starting with numbers to create the string in the first place then you should do suggested above. If you're starting with that string though, e.g. reading it from a file, then you should call DateTime.TryParseExact. You get to specify the format the input is in and the method will return a bool to indicate whether it succeeded or failed and, if it succeeded, will output the DateTime value. E.g.
C#:
var bufferDateTime = "2020,07,22,16,11,38";

if (DateTime.TryParseExact(bufferDateTime, "yyyy,MM,dd,HH,mm,ss", null, DateTimeStyles.None, var out value))
{
    Console.WriteLine(value);
}
else
{
    Console.WriteLine("Invalid input.");
}
 
If you're starting with numbers to create the string in the first place then you should do suggested above. If you're starting with that string though, e.g. reading it from a file, then you should call DateTime.TryParseExact. You get to specify the format the input is in and the method will return a bool to indicate whether it succeeded or failed and, if it succeeded, will output the DateTime value. E.g.
C#:
var bufferDateTime = "2020,07,22,16,11,38";

if (DateTime.TryParseExact(bufferDateTime, "yyyy,MM,dd,HH,mm,ss", null, DateTimeStyles.None, var out value))
{
    Console.WriteLine(value);
}
else
{
    Console.WriteLine("Invalid input.");
}
Hi, I have added "using System.Globalization";
There are issues with "var out value".

"," expected
The name var does not exist in current ....
The name value does not ........

Thanks,
 
var out value should have been out DateTime value.
 
Hi, I have added "using System.Globalization";
There are issues with "var out value".

"," expected
The name var does not exist in current ....
The name value does not ........

Thanks,
Sorry, should have been out var rather than var out. That's what I get for typing that code into the forum freehand instead of into the IDE and then pasting.
 
var out value should have been out DateTime value.
out var is fine as the DateTime type will be inferred from usage. I just got the out and var the wrong way around, and not for the first time.
 
Back
Top Bottom