1

I am using Carbon Api extension in my Yii2 Advanced Application project

My code is like below.

date_default_timezone_set('Asia/Kolkata');
$time=time();
$y = date("Y",$time); //Year eg.2017
$n = date("n",$time); //Month eg.4
$j = date("j",$time); //Day eg.4
$h = date("G",$time); //Hour eg.10 (24 Hour format)
$i = date("i",$time); //Minute eg.15
$s = date("s",$time); //Socond eg.27
$carbon_time = Carbon::create($y,$n,$j,$h,$i,$s);
$parsed_time=Carbon::parse($carbon_time);
echo $parsed_time->diffForHumans(); //Carbon Api object

How do I Shorten this above code..?

$carbon_time and $parsed_time will give the output like --> 2017-04-04 10:15:27

I'm expecting to get this as output --> "1 second ago"

Cœur
  • 37,241
  • 25
  • 195
  • 267
Gokul S
  • 41
  • 1
  • 12
  • Does this work?? http://stackoverflow.com/a/30992170/6720181 – Riddhiman Adib Apr 04 '17 at 04:57
  • I have used this method in my **Laravel project** and it worked. But i'm trying to get the same in my yii2 project but it's not working. Then i've tried the above mentioned method but it's too long. – Gokul S Apr 04 '17 at 05:06

1 Answers1

1

Carbon is just an extension of the \DateTime Object, so you can do this.

$dateTime = new Carbon('-1 month', new \DateTimeZone('Asia/Kolkata'));
echo $dateTime->diffForHumans();

If you have a timestamp you can do this

$dateTime = Carbon::createFromTimestamp(
    $myTimestamp,
    new \DateTimeZone('Asia/Kolkata')
);
echo $dateTime->diffForHumans();
Jonathan
  • 2,778
  • 13
  • 23
  • Thanks @Augwa this works for me but i'm not expecting this,I need to convert the timestamp that i've stored in the database when i save a new Post in to the database. – Gokul S Apr 04 '17 at 05:14
  • Yes i'm storing the Unix timestamp. – Gokul S Apr 04 '17 at 05:18