Convert String to Date Time

Possible duplicate:
Convert string to DateTime in C #

I am trying to convert a string in the format "20110617111051" to a date. I am currently using the String.SubString () function to extract the year, month, day, time to format a standard string, and then use Convert.ToDateTime (string). Is there any other easy way to do this?

Dim x as String="20110617110715"
Dim standard as string = x.SubString(0,4) & "-" & x.SubString(4,2) & "-" & x.SubString(6,2) 'and time
Dim dateTime as DateTime = Convert.ToDateTime(standard) 
+3
source share
2 answers

You can use DateTime.ParseExact.

DateTime date = DateTime.ParseExact(x, "yyyyMMddHHmmss", CultureInfo.CurrentCulture);

B. B.

Dim myDate as DateTime = DateTime.ParseExact(x, "yyyyMMddHHmmss", CultureInfo.CurrentCulture)
+9
source

Use DateTime.ParseExactin conjunction with the exact format of your input string. Example:

WITH#:

string input = "20110617111051";
string format = "yyyyMMddhhmmss";
DateTime dateTime = DateTime.ParseExact(input, format, CultureInfo.InvariantCulture);

VB:

Dim input As String = "20110617111051"
Dim format As String = "yyyyMMddhhmmss"
Dim dateTime as DateTime = DateTime.ParseExact(input, format, CultureInfo.CurrentCulture)

For more information about custom date and time strings, see this page .

+1
source

All Articles