0

I have a string representing a date. It's format is MM/DD/YYYY.
I need to submit it via API to a service that requires MMDDYYYY.
Should I bother with overloading this string onto some date class and 'export' as MMDDYYY or just delete the "/" sub-string wherever I find it?

Any other neat way of doing that I wasn't aware of?

Leonid Glanz
  • 1,261
  • 2
  • 16
  • 36
JasonGenX
  • 4,952
  • 27
  • 106
  • 198
  • You can use [`date_parse_from_format`](http://php.net/manual/en/function.date-parse-from-format.php) to parse the date, and `date()` to reformat it. – Barmar May 15 '15 at 20:46
  • If you're confident the format is stable your solution would work and be simplest. – John Conde May 15 '15 at 20:46
  • 1
    The question is mostly one of how much you trust your string, i'd think. – cHao May 15 '15 at 20:47

2 Answers2

3

Since you just need to remove the '/' I would do that with the following code, it will eliminate the overhead of parsing the date.

$newDate =  str_replace ('/', '', $oldDate);
cmorrissey
  • 8,493
  • 2
  • 23
  • 27
1

You can use the DateTime object in PHP (http://php.net/manual/en/class.datetime.php)

Here is how I would do it:

<?php

$myDate = '05/15/2015';

$date = DateTime::createFromFormat('m/d/Y H:i:s', "$myDate 00:00:00");
$newDate = $date->format('mdY');

echo $newDate . PHP_EOL;

?>
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63