Wednesday, February 25, 2015

Converting from a string with format to DateTime

With some data it may be necessary to display/enter it in a given format, for example a credit card expiry may be displayed/entered as 08/16 ('MM/yy' format), but still need to be stored as a DateTime.

The following method is able to convert a string of a given format into a DateTime variable.
CultureInfo provider = CultureInfo.InvariantCulture;

var myDate = DateTime.ParseExact("08/16", "MM/yy", provider).AddMonths(1).AddSeconds(-1)
By adding a month and taking away a second the date is set to the end of the month rather than the start of it.

No comments:

Post a Comment