c# - Convert string containing a date in multiple formats to a string containing a date in the "CCYYMMDD" format -
i have string contains date , time. date in of following formats:
"m/d/yyyy" or "mm/d/yyyy" or "m/dd/yyyy" or "mm/dd/yyyy".
and time either in:
"hh:mm:ss" or "h:mm:ss".
the string retrieved sql server in c# code.
how convert string containing date in format "ccyymmdd"?
var inputdate = "4/28/2006 12:39:32:429am"; //1 - parse date parts char[] delimiterchars = { '/' }; string[] dateparts = inputdate.split(delimiterchars); var month = int.parse(dateparts[0].tostring()); var day = int.parse(dateparts[1].tostring()); var year = 0; string yearstring = dateparts[2].tostring(); //strip of time year part if (yearstring.length > 5) year = int.parse(yearstring.substring(0, 4)); //2 - create date object datetime testdate = new datetime(year, month, day); //3 - format date var outputdate = testdate.tostring("yyyymmdd"); console.writeline("input date: " + inputdate); console.writeline("output date: " + outputdate); console.readline();
you can refer msdn formatting dates here . may want validation ensure you're getting valid date sql server.
Comments
Post a Comment