Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

"Format" function for C#

Status
Not open for further replies.

Craftor

Programmer
Feb 1, 2001
420
0
0
NZ
Hi all

I have a string representing the expiry date of a credit card - that should be in MMYY format e.g. "0203". I need to ensure that this is a valid date and that it is in "MMYY" format.

I tried the following:

[tt]_ccexpiry = DateTime.Parse(_ccexpiry).ToString("MMyy");[/tt]

but it returns the following error:

System.SystemException: {"String was not recognized as a valid DateTime."}

In VB6 there is a function called Format() where I could have said something like:

[tt]Format(_ccexpiry, "MMyy")[/tt]

to ensure that the string was in the correct format.

Is there any way that I could do something similar in C#?

Thanks as always

Craftor
:cool:
 
Not really an answer but a possible workaround. Why don't you prefix your string representing a credit card date with "01" ? Every month has 01 in it so that way you'll have at least all the chars that make a valid date so the function tests shouldn't barf.
 
Thanks sjc - unfortunately still no go :-( it still doesn't like my string.
 
ok, how about this then:

string thedate = "1002";
try
{
if (thedate.Length != 4)
throw new System.ArgumentOutOfRangeException();

// this is basically what you're after
DateTime dt = new DateTime(int.Parse(thedate.Substring(2, 2)), int.Parse(thedate.Substring(0, 2)), 1);

// get to last day of this month to test expiry. So add 1 month to get to the 1st of next month
// then take away 1 day to get to the last day of our original month.

dt = dt.AddMonths(1);
dt = dt.Subtract(new TimeSpan(1, 0, 0, 0, 0));

if (DateTime.Now.CompareTo(dt.Date) > 0)
throw new System.ArgumentOutOfRangeException();

MessageBox.Show("Date is valid");
}
catch (System.ArgumentOutOfRangeException)
{
MessageBox.Show("Invalid credit card date passed");
}

obviously you'll want to give the number a more rigourous test before passing it as valid. there's probably a better way to do it, but this way works.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top