How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?
if you have a date in a string with the format "ddMMyyyy" and want to convert it to "yyyyMMdd" you could do like this:
DateTime dt = DateTime.ParseExact(dateString, "ddMMyyyy",
CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");
Parsing DateTime:
To parse a DateTime, use one of the following methods:
DateTime.Parse
DateTime.ParseExact
Alternatively, you may use try-parse pattern:
DateTime.TryParse
DateTime.TryParseExact
Read more about Custom Date and Time Format Strings.
Converting DateTime to a string:
To return a DateTime as a string in "yyyyMMdd" format, you may use ToString
method.
- Code snippet example:
string date = DateTime.ToString("yyyyMMdd");
- Note upper-cased M's refer to months and lower-cased m's to minutes.
Your case:
In your case, assuming you don't want to handle scenario when date is different format or misssing, it would be most convenient to use ParseExact
:
string dateToParse = "20170506";
DateTime parsedDate = DateTime.ParseExact(dateToParse,
"yyyyMMdd",
CultureInfo.InvariantCulture);
You can convert your string to a DateTime
value like this:
DateTime date = DateTime.Parse(something);
You can convert a DateTime
value to a formatted string like this:
date.ToString("yyyyMMdd");