简体   繁体   中英

Parse String date to specific format

This is a String date:

dob = reader.GetValue(7).ToString();` return like "12/2/2012"

But I want to convert (before passing it) to this format "2012212" , I have tried

string newDate = dob.ToString("yyyMMdd")

But I got the following error:

The best overloaded method match for 'string.ToString(System.IFormatProvider)has some invalid arguments

any idea ?

You could use SqlDataReader.GetDateTime if underlying return type is DateTime

Then you just need..

reader.GetDateTime(7).ToString("yyyyMdd");

In case, if it is stored and received as a string then I would suggest converting to DateTime first and then look for specific format.

    var date = DateTime.ParseExact(dob, "dd/M/yyyy",CultureInfo.InvariantCulture);
    var formattedDate = date.ToString("yyyyMdd");

Not Exact way of getting output but it will work.

   string dob = "12/2/2012";
   string[] d1 = dob.Split('/');
   string s = d1[2] + d1[1] + d1[0];
DateTime.ParseExact(reader.GetValue(7), "dd/M/dd", System.Globalization.CultureInfo.InvariantCulture).ToString("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(dob, "ddMMyyyy", 
                                  CultureInfo.InvariantCulture);
dt.ToString("yyyyMMdd");

You can try below method to convert string to date.

IFormatProvider culture = new CultureInfo("en-US", true);   
dob = DateTime.ParseExact(reader.GetValue(7).ToString(), "dd/MM/yyyy", culture).ToString("yyyyMMdd");

Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM