【问题标题】:Date format issue for current month当前月份的日期格式问题
【发布时间】:2020-03-28 21:35:16
【问题描述】:

我数据库中的日期格式是dd/mm/yyyy。我的日期是02/01/2019, 02/03/2019, 07/05/2019。我将它们存储在varchar。 (我不能使用日期格式,因为我的整个项目会搞砸。)

在这我只想要当月的日期 例如:

$currentMonth = date('m'); 
$receipt = DB::table('receipt_payment')
    ->whereRaw('MONTH(due_date) = ?', [$xcurrentMonth])
    ->get();

但我收到count()==0

【问题讨论】:

  • 那么,首先要做的就是将这些数据转移到日期列中。
  • 这能回答你的问题吗? mySQL convert varchar to date
  • “我不能使用日期格式,因为我的整个项目会搞砸” - 然后我会认真考虑重构代码,以便它可以使用数据库中的适当日期列进行处理.
  • 实际上你当前的代码是一团糟。使用datedateTimecolumn 实际上会更正它。
  • I cannot use date format as my whole project will mess up. 这仅仅意味着整体架构很糟糕(从数据库和代码的角度来看)。我会考虑重写这样的代码。您的查询的问题是......您仍然可以这样做,但是如果您使用正确的数据类型来存储日期(或者您可能想要使用 int 几个月),那么您的查询将比什么快得多如果您使用从字符串到月份数的转换,就会出现这种情况。

标签: php sql laravel


【解决方案1】:

您好,您可以尝试在 mysql 中将字符串转换为日期。

您可以使用str_to_date()

供参考https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_str-to-date

$currentMonth = date('m'); 
$receipt = DB::table('receipt_payment')
    ->whereRaw('MONTH(str_to_date(due_date , '%m/%d/%Y')) = ?', [$xcurrentMonth])
    ->get();

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    相关资源
    最近更新 更多