I need to convert an string date with format yyyyMMdd
to a date string with format MM/dd/yyyy
. Which is the best to do it?
I'm doing this:
DateTime.ParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture).ToString("MM/dd/yyyy")
But I'm not sure, i think there must be a better way. What do you think?
Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.
string strDate = DateTime. Now. ToString("MM/dd/yyyy");
Your way is totally OK.You may try doing this:-
string res = "20130908";
DateTime d = DateTime.ParseExact(res, "yyyyMMdd", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString("MM/dd/yyyy"));
Just for reference from MSDN:-
The DateTime.ParseExact(String, String, IFormatProvider) method parses the string representation of a date, which must be in the format defined by the format parameter.
What you are doing is fine.
Probably you can improve it by using DateTime.TryParseExact
and on successful parsing, format the DateTime
object in other format.
string dateString = "20130916";
DateTime parsedDateTime;
string formattedDate;
if(DateTime.TryParseExact(dateString, "yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsedDateTime))
{
formattedDate = parsedDateTime.ToString("MM/dd/yyyy");
}
else
{
Console.WriteLine("Parsing failed");
}
Your code is in fact the best (of course better using TryParseExact
), however looks like your input string is in the correct format (convertible to DateTime
), you just want to re-format it, I think using some string method will help. But I would like to use Regex
here:
string output = Regex.Replace(input, "^(\\d{4})(\\d{2})(\\d{2})$", "$2/$3/$1");
//E.g
input = "20130920";
output = "09/20/2013";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With