CakePHP:显示年龄的时间助手
我有一个 MySQL DATETIME 字段,用于保存用户的出生日期。我想使用该日期来显示用户的年龄(以年为单位)。
Time core helper 有没有办法做到这一点?
另外,为什么当您向 Cake 中的表单添加 DATETIME 字段时,它不允许您选择小于 1990 年的日期?
谢谢,
琼斯
I have a MySQL DATETIME field that holds the date of birth of a user. I want to use that date to display the age the user in years.
Is there a method of the Time core helper to do this?
Also, why when you add a DATETIME field to a form in Cake does it not let you select a date less than 1990?
Thanks,
Jonesy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
该函数名为 timeAgoInWords ,
end 参数的意思是用单词显示之前的时间,直到日期小于 150 年(至少我还没听说过 150yo man :))))。
目前的结果是: 出生: 34 岁零 9 个月零 4 周之前
但还要按照 Jason 的建议检查 API 和 CookBook
the function is called timeAgoInWords
The end parameter mean to display the time ago with words until the date is less than 150 years (at least I haven't heard of 150yo man :)))).
The current result is: born: before 34 years, 9 months, 4 weeks
But also check API and CookBook as Jason suggest
添加新答案,因为代码会显示得更好。我将如何做到这一点:
在您的模型中创建 虚拟字段 像这样。
然后将其用作模型中的普通场。 :)
Adding new answer because the code will be shown better. How I would do that:
in your model create virtual field like this.
Then use it as normal field in the model. :)
timeAgoinWords()
可能会执行您想要的第一部分操作。查看 Book这与自动表单字段有关。您可以使用选项调整年份范围。查看图书。
timeAgoinWords()
may do what you want for the first part. Check out the BookThis has to do with the automagic form fields. You can adjust the year range with options. Check out the Book.
您可以使用标准 PHP 函数执行计算 - 查看日期部分。我不会告诉你如何做,因为你自己做会学到很多东西。
我会说你需要小心才能得到准确的结果。 365 天并不总是一年,一个月的天数也不同。
您可以在 Cake 表单助手中配置日期选择范围。
You can perform the calculation using standard PHP functions - look in the date section. I'm not going to tell you how to do it because you'll learn a huge amount by doing it yourself.
I will say that you need to be careful to get an accurate result. 365 days is not always a year and a month has a variable number of days.
You can configure the date selection range in the Cake form helper.
我总是使用这种经过测试的方法:
它可能可以被重构
但它适用于闰年和各种东西。所以我从来没有打扰过...
它使用一个你没有的常量
:define('FORMAT_DB_DATE', 'Ymd');
i always use this tested method:
it can probably be refactured
but it works with leap years and all kinds of stuff. so i never bothered...
it uses a constant you dont have
its just: define('FORMAT_DB_DATE', 'Y-m-d');