1

I'm currently getting the user's birthday from Facebook and storing it in the standard m/d/Y that Facebook supplies (Ex: 05/21/1982). I have an edit profile page in which I need to assign the day, month and year to 3 separate variables in order to allow the user to change his or her birthday as well as pre-select the correct birthday.

My code that pertains to only the days variable which I would want to be assigned to $days_var and in the above example of 05/21/1982 would be 05 is pasted below:

<?php
$days = range(1, 31);
foreach($days as $day) {
?>
<option value="<?php echo($day) ?>" <?php if ($days_var = $day){echo "selected='1'";}?> ><?php echo($day) ?></option>
<?
}
?>

Thanks. EDIT: I have only given the days example but would obviously need the day, month and year variables.

user1011713
  • 281
  • 5
  • 23
  • Here is [a relevant read about creating select options from a range of integers](https://stackoverflow.com/a/71790975/2943403). – mickmackusa May 02 '22 at 03:22

4 Answers4

4

You're needing to parse the date string into its constituent components? How about:

list($month_var, $days_var, $year_var) = explode('/', $dateString);
curtisdf
  • 4,130
  • 4
  • 33
  • 42
2

See PHP's datetime class or the strtotime() and date() functions

Cameron Martin
  • 5,952
  • 2
  • 40
  • 53
1

Like ddlshack says, use strtotime() and date(),

And for future references,

It's

if ($days_var == $day)

not

if ($days_var = $day)
Hyunmin Kim
  • 931
  • 2
  • 8
  • 18
0

It will be rather poor UX or result in tedious javascripting to provide three separate date component fields. This is because not all month-year combinations have the same number of days.

Instead pass the full date expression to a single html <input type="date" value="$date"> tag.

See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date for more information.

When it comes to presenting a date string to the end user, you are welcome to use any format you like. When transferring the data between layers or pages of your application, standardize the data as Y-m-d -- this will improve processing functionality and codability in javascript, php, and sql.


If you'd rather ignore the good advice above, you can parse your date string with: (Demos)

For potentially zero-padded month and day strings:

  1. sscanf($date, '%[^/]/%[^/]/%s', $m, $d, $y);
  2. [$m, $d, $y] = explode('/', $date);
  3. $dateObject = DateTime::createFromFormat('m/d/Y', $date); then
    $m = $dateObject->format('m');
    $d = $dateObject->format('d');
    $y = $dateObject->format('Y');

For values directly cast as integer types:

sscanf($date, '%d/%d/%d', $m, $d, $y);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136