定义PHP脚本运行时的日期时间(Define date time at run time of PHP script)

编程入门 行业动态 更新时间:2024-10-09 07:29:07
定义PHP脚本运行时的日期时间(Define date time at run time of PHP script)

我目前正在开发一个管理电子商务网站交付规则的应用程序。 我需要测试一周中的某些日子和一天中的时间来测试他们有不同的交付规则。 不幸的是,我正在使用多个其他项目的服务器上工作,因此无法编辑OS时间/日期。

类似于date_default_timezone_set如何定义时区并设置脚本中所有日期/时间函数使用的默认时区 。 有什么我可以在我的脚本开始运行,以全面定义时间和日期,并在全球范围内应用? 我真的很想测试圣诞节的时间。

I'm currently developing an application which manages delivery rules for an e-commerce website. I need to test certain days of the week and times of the day to test they have different delivery rules. Unfortunately, I'm working on a server with multiple other projects so can't edit the OS time/time date.

Similar to how date_default_timezone_set can define the timezone and sets the default timezone used by all date/time functions in a script . Is there something I can run at the start of my script to define the time and date in full and is globally applied? I really would like to test Christmas time for example.

最满意答案

我不知道任何这样的PHP函数。 据我所知,这些信息是直接从操作系统中获取的。

为了简化测试,你可以做什么,只需要一个方法来获取当前日期/时间戳。 这将允许更简单的单元测试。

例如,如果您需要获取当前日期,则可以在函数的某个位置获取。

实用程序类:

class DateUtility { public static function getCurrentDate() { if (!Config::get('debug')) { return date('j-M-Y'); } return date('j-M-Y', mktime(0, 0, 0, Config::get('debug-month'), Config::get('debug-day'), Config::get('debug-year')); } }

用法示例:

$date = DateUtility::getCurrentDate(); set_delivery_date($date);

请注意,这个例子非常简单。 你很可能需要在你的系统中有一个更一般的实现,特别是如果你处理很多日期,时区和类似的东西。 还要注意,如果你在MySQL(或类似的)中使用NOW()等函数,这是否需要特别处理?

I am not aware of any such functions for PHP. As far as I know is this information directly fetched from the operating system.

What you could do, to ease testing, is to have a single method for fetching the current day/timestamp. This would allow simpler unit testing.

For example, if you need to fetch the current date, somewhere in your function.

Utility class:

class DateUtility { public static function getCurrentDate() { if (!Config::get('debug')) { return date('j-M-Y'); } return date('j-M-Y', mktime(0, 0, 0, Config::get('debug-month'), Config::get('debug-day'), Config::get('debug-year')); } }

Example usage:

$date = DateUtility::getCurrentDate(); set_delivery_date($date);

Note that this example is extremely simplified. You most likely need to have a more general implementation in your system, especially if you deal a lot with date, timezones and stuff like that. Also note that if you use functions such as NOW() in MySQL (or similar), will this need to be handled specially too.

更多推荐

本文发布于:2023-04-29 09:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335567.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   定义   日期   时间   run

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!