Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String to Datetime C#

Tags:

c#

.net

I have a string value which is a datetime : "20100825161500" and I want to convert this to a System Datetime. I have tried Convert.ToDateTime and DateTime.Parse and these do not work.

like image 274
MartGriff Avatar asked Sep 01 '10 08:09

MartGriff


People also ask

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How do I convert a string to a date in C #?

You can use the methods like Convert. ToDateTime(String), DateTime. Parse() and DateTime. ParseExact() methods for converting a string-based date to a System.

What is ParseExact C#?

ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.


2 Answers

You can use DateTime.ParseExact to pass the format you need.

Here is an example:

var parsed = DateTime.ParseExact("20100825161500","yyyyMMddHHmmss", null);

Possible format values are listed at Standard Date and Time Format Strings and Custom Date and Time Format Strings

like image 122
Giorgi Avatar answered Sep 24 '22 23:09

Giorgi


Try to use something like this

Datetime D = DateTime.ParseExact("20100825161500","yyyymmdd...",null)

here you have a link about how to make you "format" string

like image 43
Jonathan Avatar answered Sep 26 '22 23:09

Jonathan