Ann
Ann

Reputation: 471

How do I write the code without "strtotime"

How do I write this code without strtotime conversion.

The date of birth come from database.I want to display it in d/m/y format

<?php 
  echo  date('d/m/Y', strtotime($form_data["personal_info"]->date_of_birth)) ;
    ?>

Upvotes: 0

Views: 60

Answers (2)

felipsmartins
felipsmartins

Reputation: 13549

It should be work:

$stringDate = '2015-09-22'; # maybe a MySQL date string

echo DateTime::createFromFormat('Y-m-d', $stringDate)->format('d/m/Y');

Procedural style:

echo  date_format(date_create_from_format('Y-m-d',$stringDate), 'd/m/Y');

Even though it seems verbose, it turns on the code a lot more explicit. Someone who reading this code at first glance can understand what is going on.
But if you're just concerned about concise code, it's okay using strtotime().

Also, you can format date via SQL (MySQL):

mysql> SELECT DATE_FORMAT('2015-09-22', '%d/%m/%Y');
+---------------------------------------+
| DATE_FORMAT('2015-09-22', '%d/%m/%Y') |
+---------------------------------------+
| 22/09/2015                            |
+---------------------------------------+
1 row in set (0.10 sec)

Despite it has influence on cache.

Upvotes: 3

I-Kod
I-Kod

Reputation: 189

You can use the Carbon a simple PHP extension Find more details here Click to find more details

public function getDobAttribute($value)
    {
        return Carbon::parse($value)->format('d/m/Y');
    }

    public function setDobAttribute($value)
    {
        $this->attributes['dob'] = Carbon::createFromFormat('d/m/Y', $value)->toDateString();
    }

Upvotes: 0

Related Questions