【问题标题】:get current date with country after setLocale in laravel在 laravel 中的 setLocale 之后获取国家/地区的当前日期
【发布时间】:2020-07-25 16:31:25
【问题描述】:

我想根据几个国家/地区显示当前日期。我用了这段代码

$mytime = Carbon\Carbon::now();
echo $mytime->toDateTimeString();

我按国家/地区在中间件中使用 setLocale() 方法。但是 $mytime 所以返回了当前的服务器日期。真正的解决方案是什么?

【问题讨论】:

  • 试试Carbon::now()->locale('xx_XX');
  • 语言环境与格式有关。如果您还想获取本地时间,请同时设置时区
  • 我使用了这个,但返回了当前服务器时间。

标签: php laravel date php-carbon


【解决方案1】:

Carbon 使用默认的DateTime PHP 对象,例如:

Carbon::now('Europe/London');

因此,如果您希望将时区与 Carbon 结合使用。那么它应该匹配 PHP DateTime TimeZone 格式
List of Supported TimeZone on PHP

【讨论】:

    【解决方案2】:

    我首先得到了默认服务器日期。然后我就可以通过 date_default_timezone_set 方法(“亚洲/德黑兰”)获得伊朗的日期和时间。再次使用这个函数,我们可以得到我们想要的任何国家的历史

     date_default_timezone_set("Asia/Tehran");
        $persianDate = new \DateTime(Carbon::now()->toDateTimeString());
        $persianDate = $persianDate->format('Y-m-d H:i');
    
        date_default_timezone_set("Europe/Istanbul");
        $TurkishDate = new \DateTime(Carbon::now()->toDateTimeString());
        $TurkishDate = $TurkishDate->format('F d Y');
    
        date_default_timezone_set("Asia/Seoul");
        $koreanDate = new \DateTime(Carbon::now()->toDateTimeString());
        $koreanDate = $koreanDate->format('F d Y');
    
        date_default_timezone_set("Europe/London");
        $londonDate = new \DateTime(Carbon::now()->toDateTimeString());
        $londonDate = $londonDate->format('F d Y');
    

    如果您使用网站的所有页面

        View::share("persianDate",$persianDate);
        View::share("turkishDate",$TurkishDate);
        View::share("koreanDate",$koreanDate);
        View::share("londonDate",$londonDate);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-18
      • 1970-01-01
      • 2015-07-20
      • 2022-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多