views:

123

answers:

5

i am having a problem converting a datetime which is in string format but iam not able to convert it to yyyyMMdd format.

my code is :

string tpoc = refSubClaim.BenefitsFolder.BenefitFolderIdNumber.ToString();
                                string[] tpocinfo = Regex.Split(tpoc,";");

                                for (int i = 0; i < tpocinfo.Length; i++)
                                {
                                    switch (i)
                                    {
                                        case 0:
                                            {
                               string[] tpoc2 = Regex.Split(tpocinfo[0], ",");
                               claimantAuxillaryRecord.TPOCDate2 = tpoc2[0].ToString();
                    claimantAuxillaryRecord.TPOCAmount2 = Convert.ToDecimal(tpoc2[1]);
                                            claimantAuxillaryRecord.FundingDelayedBeyondTPOCStartDate2 = tpoc2[2].ToString();
                                            }
                                            break;
+10  A: 

To parse a DateTime, use one of the following methods:

You can parse date by exact format provided by you, or by culture-specific format (for details, see above links).

To return a DateTime as string in "yyyyMMdd" format, use this:

ventr1s
+4  A: 

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");
SLaks
A: 

Based on the property names it looks like you are trying to convert a string to a date by assignment:

claimantAuxillaryRecord.TPOCDate2 = tpoc2[0].ToString();

It is probably due to the current UI culture and therefore it cannot interpret the date string correctly when assigned.

Peter
no its a string with yyyy/mm/dd and i need it in yyyyMMdd format
Ashutosh
and while doing claimantAuxillaryRecord.TPOCDate2 = tpoc2[0].ToString("yyyyMMdd");it gives some build errors.The best overloaded method match for 'string.ToString(System.IFormatProvider)' has some invalid arguements
Ashutosh
+1  A: 

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");
Falle1234
A: 

You could use DateTime.TryParse() instead of DateTime.Parse().
With TryParse() you have a return value if it was successful and with Parse() you have to handle an exception

peter