【问题标题】:Check if a parameter is already formatted as a date检查参数是否已格式化为日期
【发布时间】:2020-08-08 03:50:46
【问题描述】:

如何检查参数是否已经格式化?

$start_date = DateTime::Format::Pg->format_date($start_date);
$end_date = DateTime::Format::Pg->format_date($end_date);

更具体地说,我想在格式化之前检查参数 $start_date 和 $end_date 是否已格式化,因为如果它们已经格式化,我会收到错误消息。谢谢!

【问题讨论】:

  • 也许日期和时间正则表达式的Regexp::Common::time 模块会有所帮助。
  • 你得到什么错误?
  • 我没有收到错误信息? perl -MDateTime::Format::Pg -wE'$dt = q(2003-01-16 23:12:01); $obj = DateTime::Format::Pg->parse_datetime($dt); say $obj; $bb = DateTime::Format::Pg->parse_datetime($obj); say $bb'。就像您希望的那样打印出完全相同的内容

标签: perl mojolicious


【解决方案1】:

这不完全是您的问题,但这是我复制到我的大多数项目中的一段常见代码:

=head2 format_datetime

  ->search({ date_col => { '>=' => $schema->format_datetime( $myDate ) } })

Utility method to properly format a DateTime according to the current storage
engine.  Optional second argument converts the datetime to a specific time zone
before stringifying.

=cut

sub format_datetime {
   my ($self, $datetime, $time_zone)= @_;

   # Make a datetime if it isn't already
   $datetime= DateTime::Format::Flexible->parse_datetime($datetime)
      unless ref $datetime && ref($datetime)->can('set_time_zone');

   # Force time zone
   $datetime= $datetime->clone->set_time_zone($time_zone)
      if defined $time_zone and $datetime->time_zone ne $time_zone;

   $datetime->set_time_zone('floating'); # prevent datetime formatter from changing time zone
   return $self->storage->datetime_parser->format_datetime($datetime);
}

请注意,我使用的是 DBIx::Class,并且此方法进入了 Schema 类。但无论如何,关键是我检查该值是否是 DateTime 对象,如果不是,我解析它,然后我设置正确的时区(如果它已经是一个 DateTime 对象,它的时区与应该存储的不同列),然后我使用数据库引擎的格式化程序将其转换回字符串。

通过使用这样的帮助程序,我不再依赖于特定的日期格式化程序,并且可以在 SQLite 上运行我的测试用例。

【讨论】:

    猜你喜欢
    • 2011-10-06
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 2018-07-22
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    相关资源
    最近更新 更多