Siva Ganesh
Siva Ganesh

Reputation: 1445

How to insert AM and PM in Mysql Database?

This is my value, I am going to insert in my DB

[phoneinterview] => 2018-05-16 10:28 PM

In My databse I have field like this

phoneinterview  timestamp

But Its Inserting Like this:

2018-05-16 10:28:00     

Actually I want to insert like this:

2018-05-16 10:28 PM

Upvotes: 2

Views: 6654

Answers (4)

Hiren Gohel
Hiren Gohel

Reputation: 5042

As you are using datetime datatype it's storing 2018-05-16 10:28:00. But if you want to store AM/PM you need to use varchar datatype.

I suggest you to use ->format(); while you get the timestamp data. This will convert the date time format as your wish.

For now, as you want to display AM/PM after time, use it like: ->format('g:i A'); This will show time like 10:28 PM.

Hope this helps you!!

Upvotes: 1

Mike
Mike

Reputation: 24383

MySQL uses the format 'Y-m-d H:i:s' to store dates, so if you're using anything other than that, you need to convert it to this format first. This can be done with DateTime::createFromFormat():

$date = DateTime::createFromFormat('Y-m-d g:i a', '2018-05-16 10:28 PM');

This will create a DateTime object that you can easily format for MySQL:

$date->format('Y-m-d H:i:s');

Upvotes: 1

Michiel
Michiel

Reputation: 2203

If you use a datetime field in your database you can't, but if you change the field to a varchar then you are able to save it the way you like it. I would recommend against it. Why would you want to save a formatted time? It is best practice to save the date in a datetime field, and then when you want to show it format the way you want to. In Laravel you can do this using a mutator like this:

public function getPhoneinterviewAttribute() {
    return \Carbon\Carbon::now(
        $this->attributes['phoneinterview']
    )->format('g:i A');
}

Plus side: When you are expanding to areas where people don't use AM/PM then you can easily format it to their locale.

Upvotes: 2

Kishen Nagaraju
Kishen Nagaraju

Reputation: 2190

Ok. When you are selecting timestamp or datetime datatypes for storing date, it does not store the AM and PM values in the database table fields. The best solution for this is you retrieve the date and convert that into date and time along with AM/PM manually.

One alternate solution is using the datatype of varchar instead of timestamp but that is not recommendable.

Upvotes: 1

Related Questions