简体   繁体   English

从Timestamp php中减去6个月的最简单方法是什么

[英]What is the easiest way to substract 6 months from Timestamp php

I have a date in timestamp format. 我有一个时间戳格式的日期。 From which I need to subtract 6 months from it. 从中我需要减去6个月。 This is the current way I do this 这是我目前的做法

 $begin = Carbon::createFromTimestamp($begin, Timezone::IST)->subMonths(6);

But I again the need the timestamp format since I save this as integer (laravel). 但是我再次需要时间戳格式,因为我将其保存为整数(laravel)。 Is there a better way of doing this 有没有更好的办法做到这一点

Like this 像这样

 $Datetime = new DateTime($time);
 $Datetime->modify('-6 months');
 echo $Datetime->format('Y-m-d');

http://php.net/manual/en/class.datetime.php http://php.net/manual/en/class.datetime.php

UPDATE UPDATE

What is this? 这是什么?

But I again the need the timestamp format since I save this as integer (laravel). 但是我再次需要时间戳格式,因为我将其保存为整数(laravel)。 Is there a better way of doing this 有没有更好的办法做到这一点

I mean what does the int look like. 我的意思是int是什么样的。 You can use something like this DateTime::createfromformat( 'Ym-d', '2018-01-01') And then output it as a timestamp with $Datetime->gettimestamp(); 您可以使用类似DateTime::createfromformat( 'Ym-d', '2018-01-01') ,然后使用$Datetime->gettimestamp();将其输出为时间戳$Datetime->gettimestamp();

So the full code would close to: 因此完整的代码将接近:

$Datetime- = DateTime::createfromformat( '{your date format}', $datestring);
$Datetime->modify('-6 months');
$timestamp = $Datetime->gettimestamp();

You should not subtract an arbitrary number of seconds, because that wont account for leap years, or months with odd numbered days. 您不应减去任意秒数,因为这不会说明leap年或带奇数天的月份。 Date time relative formats are provided especially for doing this, so it's best to use them. 特别提供了日期时间相关格式,因此最好使用它们。

UPDATE2 ( for Carbon ) UPDATE2 (用于Carbon)

If you look at the source for Carbon its an extension of DateTime and thus probably provides the same functionality, and a bit more. 如果您查看Carbon的源代码,它是DateTime的扩展,因此可能提供相同的功能,甚至更多。 So even this may work Carbon::createFromTimestamp($begin, Timezone::IST)->subMonths(6)->gettimestamp() 所以即使这可能也可以工作Carbon::createFromTimestamp($begin, Timezone::IST)->subMonths(6)->gettimestamp()

As this tid bit from the carbon source shows 正如来自碳源的潮汐显示

public function diffInSeconds(Carbon $dt = null, $abs = true)
{
    $dt = $dt ?: static::now($this->getTimezone());
    $value = $dt->getTimestamp() - $this->getTimestamp();
    return $abs ? abs($value) : $value;
}

Specifically $this->getTimestamp() , this is no big surprise as it extends DateTime. 特别是$this->getTimestamp() ,这并不奇怪,因为它扩展了DateTime。 That said, I would avoid using the public property of timestamp as it violates the Black Box Protocol ( this is what I call it (BBP)) where a class should be a black box for it's functionality. 就是说,我会避免使用timestamp的公共属性,因为它违反了Black Box协议(这就是我所说的(BBP)),在该协议中,类应该是其功能的黑盒。 And you should only access data from a class using it's public interface ( which interfaces do not contain properties ) That's just my Opinion though. 而且,您仅应使用其公共接口(该接口不包含属性)访问类中的数据,但这只是我的意见。

Now if you were to really dig into the source code for carbon, then this code Carbon::createFromTimestamp($begin, Timezone::IST)->subMonths(6) probably does something very much like this: 现在,如果您真的要研究碳的源代码,那么这段代码Carbon::createFromTimestamp($begin, Timezone::IST)->subMonths(6)可能会执行以下操作:

$this->datetime = new Datetime($begin, Timezone::IST);
$this->datetime->modify('-6 months');

Specifically 特别

class Carbon extends DateTime{

     //-------- create---------

     public static function createFromTimestamp($timestamp, $tz = null)
    {
        return static::now($tz)->setTimestamp($timestamp);
    }

    public static function now($tz = null)
    {
        return new static(null, $tz);
    }
     /*
        the code "new static" can be a bit confusing, but this is just           
        one of many ways to call "new Carbon()", which in turn is calling
        new "DateTime()". They use static so if you extended Carbon it will
        work (as opposed to using "new self") a.k.a "new static" uses late   
        static binding.  And they also use static, because it's cleaner then
        doing something like "new __CLASS__", which I believe will not let
        you pass in arguments (without assigning the class name to a 
        variable). Where as new static($arg) works fine.  In any case it's
        generally preferred to use something like "new static" then to
        reference the class name directly as in "new Carbon".  Obviously
        this is so if the class name changes there are no repercussions on
        the code, no code to update.
    */

    //-------- subMonth ---------
    public function subMonth($value = 1)
    {
        return $this->subMonths($value);
    }

    public function subMonths($value)
    {
        return $this->addMonths(-1 * $value);
    }

    public function addMonths($value)
   {
        if (static::shouldOverflowMonths()) {
            return $this->addMonthsWithOverflow($value);
        }
        return $this->addMonthsNoOverflow($value);
    }

    public function addMonthsWithOverflow($value)
    {
        return $this->modify((int) $value.' month');
    }

    public function addMonthWithOverflow($value = 1)
    {
        return $this->addMonthsWithOverflow($value);
    }

}

So it calls like 4 or 6 additional function calls, but in the end it's basically the same. 因此,它的调用类似于4或6个其他函数调用,但最后基本上是相同的。 Taken right from the github source code . 直接取自github源代码

For creating they are just making a DateTime object (child) with the current day and then setting the date in it with the timestamp. 为了创建它们,他们只是用当前日期制作一个DateTime对象(子对象),然后使用时间戳设置其中的日期。

All they are doing is taking the 6 you give them *-1 so it's -6 then doing $this->modify('-6 months') which as it extends DateTime is roughly equivalent. 他们所做的就是将6给您*-1所以它是-6然后做$this->modify('-6 months') ,因为它扩展了DateTime所以大致相等。

Basically all the code I pasted above, can be done in 3 lines. 基本上,我上面粘贴的所有代码都可以在3行中完成。 But, if it was me I would still use Carbon, as it's the "frameworks" way of doing it, so it's a tad bit more proper. 但是,如果是我,我仍然会使用Carbon,因为这是“框架”的实现方式,所以它有点合适。 Also function calls are cheep, and performance wise you wont really notice the few nanosecond difference. 函数调用也很便宜,在性能方面,您不会真正注意到几纳秒的差异。 So as always I would lean to Readability ( within the framework ) over performance. 因此,与往常一样,我会倾向于在性能方面(框架内)可读性。

As a side I never used Carbon but it looks interesting. 一方面,我从未使用过Carbon但看起来很有趣。 I delved a bit deeper then I probably should have, but I have been thinking of making something very similar, so perhaps I will just "composer in" Carbon ... lol ... The older I get the lazier I am, 6 years ago, I would have just hammered away at the keys tell I had something very similar to it. 我深入研究了可能应该做的事,但是我一直在考虑做一些非常相似的事情,所以也许我只是“碳”中的“作曲家”……大声笑……我年纪大一点了,才6岁以前,我只是会敲击按键,告诉我有一些非常相似的东西。 But composer wasn't around then, so ... 但是当时还没有作曲家,所以...

You can just use ->timestamp : 您可以只使用->timestamp

$begin = Carbon::createFromTimestamp($begin, Timezone::IST)->subMonths(6)->timestamp;

But if you're saving this and all other dates to DB as timestamps, you can set $dateFormat property to U : 但是,如果将此日期和所有其他日期保存为DB作为时间戳,则可以将$dateFormat属性设置为U

protected $dateFormat = 'U';

Then, $begin will be converted to Carbon instance automatically by Laravel. 然后,Laravel将自动将$begin转换为Carbon实例。 So, you could just do this: 因此,您可以这样做:

$begin->setTimezone(IST')->subMonths(6);

And then just save it back to DB without manually converting it back to timestamp. 然后只需将其保存回数据库,而无需手动将其转换回时间戳。

https://laravel.com/docs/5.5/eloquent-mutators#date-mutators https://laravel.com/docs/5.5/eloquent-mutators#date-mutators

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM