简体   繁体   中英

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

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.

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.

MySQL uses the format 'Ymd 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');

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!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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