我bootstrap-material-datetimepicker在我的 Symfony 表單上使用,因此用戶可以選擇他的生日。datetimepicker例如返回一個字符串"Saturday 16 May 2020"。我想age從那個字符串生日計算用戶的(整數)!如何計算年齡?有沒有辦法讓日期時間返回日期或 int 而不是字符串?我的表格代碼:{% extends 'base.html.twig' %}{% block body %} {{ form_start(form, {attr: {novalidate: 'novalidate'}}) }} <div class="form-line"> {{ form_widget(form.birthday, {'attr': {'class': 'datepicker form-control', 'placeholder': 'Date of Birth'} }) }} </div> {{ form_rest(form) }} {{ form_end(form) }} {% endblock %}實體代碼:/** * @ORM\Column(type="string", nullable=true) */private $birthday;public function getBirthday(): ?string{ return $this->birthday;}public function setBirthday(?string $birthday): self{ $this->birthday = $birthday; return $this;}
1 回答

GCT1015
TA貢獻1827條經驗 獲得超4個贊
你有2個選擇:
將生日更改為日期時間類型的字段,并在表單中使用 BirthdayType。
->format('Y-m-d')
然后,當您想在控制器中將其顯示為字符串或使用 twig 的過濾器時,您必須格式化該字段,|date('Y-m-d')
因為這$user->getBirthday()
將返回一個 DateTime 對象。當您想要計算年齡(即:)時,從該字段中的字符串創建一個新的 DateTime 對象
new \DateTime($user->getBirthday()
。
diff()
當您擁有 DateTime 對象時,您所需要做的就是為“今天”創建一個新對象,并使用 DateTime 對象的方法或 PHP 的函數計算與那里的差異date_diff()
。
- 1 回答
- 0 關注
- 137 瀏覽
添加回答
舉報
0/150
提交
取消