Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Date String to another Date string with different format

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?

like image 695
Müsli Avatar asked Sep 16 '13 15:09

Müsli


People also ask

How do I change one date format to another date in Python?

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.

How do you convert strings from mm/dd/yyyy to date?

string strDate = DateTime. Now. ToString("MM/dd/yyyy");


3 Answers

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.

like image 33
Rahul Tripathi Avatar answered Sep 19 '22 05:09

Rahul Tripathi


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");
}
like image 138
Habib Avatar answered Sep 20 '22 05:09

Habib


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";
like image 27
King King Avatar answered Sep 20 '22 05:09

King King