Date conversion from db to display - php

I'm reading a datetime field from mysql db. I'd like to convert it in PHP:
from: 2009-05-23 14:46:23
to 05/23/2009 02:46 pm
Notice the am/pm conversion.
Thanks in advance..

// assume you retrieve the mysql date in variable $date
date("m/d/Y h:i a", strtotime($date));

Call me old fashioned. I store all dates as epoch, and if I will ever go outside my timezone, as epoch of UTC of the date.
Epoch is seconds since Jan 1st, 1970 or something like that.
Known in MySQL as Unixtime. FROM_UNIXTIME(), etc..
$epoch = strtotime($mdate);
You can also store dates directly in MySQL with data type DATETIME if you are so inclined.
Your chosen format is a drop in replacement actually.

Depending on the type that's return by your db code, you can create a new DateTime object or format an existing one with date_format(). From the example you give, the date format string should be "m/d/Y h:i a". Note that the conversion from 24h to 12h is handled in either case.
Have a look at the format options for DateTime:date() and DateTime:format() (date_format is an alias for this)

Related

How to convert two different strings to date and store it in single column in MySQL database?

Currently I'm working on PHP and MySQL Project. I'm taking DATE INPUT from users in string format. So user can enter any format in text-box. For e.g. dd/mm/yyyy or dd-mm-yyyy or yyyy-mm-dd or mm/dd/yyyy etc. (I know its too bad practice). But my question is:
is it possible to convert these all in single format and store it in
single column?
.
For converting I'm using str_to_date() function, but it accepts only one format to convert. How can I add other formats to convert string to date ?
try this, should work:
$mysqlFormatedDate = date('Y-m-d H:i:s', strtotime($yourTime));
PHP will take $yourTime and resolve it's format, then it will convert it to unix timestamp, and then it will convert to mysql datetime format which is Y-m-d H:i:s then you just need to save it to your DB.
you can do this in your mysql_query using STR_TO_DATE:
STR_TO_DATE($yourTime, '%c/%e/%Y %r')
You can use "RLIKE()" to check fo some patterns but that will fail because you can't differentiate between international and retarded. Imagine someone typing in "12/11/2018". Is it the 11th of December or 12th of November? Also you wrote "e.g.", so if you allow everything, what would you make of "20122007"? 20th December 2007, 20th July 2012?
Use a JS-Library for date inputs or do inputs for day, month and year separately. Otherwise it's pretty hopeless.

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
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.
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.
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');
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!!

php date to mysql returns 0's

Hello i am trying to add a date time from PHP into my MySQL database, in the database I have tried date time and time stamp and I have tried it with and without current_time set as the default option, in my php I have the following.
date_default_timezone_set("Europe/London");
$date = date('m/d/Y h:i:s a');
My hope was to just add the $date into the value's part of the upload query however in all cases it comes back as 0's, it echo's the date fine, however it uplaod's 0's, any help is appreciated, Thanks.
'm/d/Y h:i:s a is not a standard MySQL datetime format so unless you are storing it as varchar/char you will get the results you are seeing.
Your options are to:
Store the date in a standard format (datetime Y-m-d H:i:s, timestamp) and convert it to whatever format you want during the query (recommended)
Store it as a string but lose all of the datetime functionality MySQL offers. Losing this functionality will make working with dates in your queries and PHP very painful and is not recommended to do.

Date between MySQL and PHP

I have a table with a field of type date within a MySQL database. My user places a date into a field (format dd-mm-yyyy) which I convert into yyyy-mm-dd for insertion into the database. This works fine. I can see the date in there as (for example) 2012-04-04.
My issue is that I then select this record, convert the date to the format I wish to display (dd-mm-yyyy) and get 03-04-2012. I understand why, in that my database is set to UTC, however the user is on Berlin time, therefore 04-04-2012 00:00 in Berlin is 03-04-2012 23:00 UTC.
The issue means that if I then save the displayed date (03-04-2012), the next time I see it, it displays as 02-04-2012 because I saved only the date and therefore the system is assuming a 00:00 time again.
I cannot see a way around this other than setting this as a datetime type rather than a date type, however I would rather not do that as time (for various reasons) is stored in a separate field. Any suggestions?
When you inserting a record you add as datetime current UTC time, after that every user in their profile may want to/or set his timezone.
If you know the timezone of the user u can easy convert the datetime to user locale time. Because you know the differences in hours/minutes between the time.
P.S. You can store the datetime as varchar and save the unix timestamp in this field. Unix timestamp is based on current timezone I think.
UPDATE:
I think that might help
$date = time();
dump(date('d-m-Y H:i:s', $date)); // 03-04-2012 08:43:38
date_default_timezone_set('Europe/London');
dump('London: '. date('d-m-Y H:i:s', $date)); // London: 03-04-2012 11:43:38
date_default_timezone_set('Europe/Berlin');
dump('Berlin: '. date('d-m-Y H:i:s', $date)); // Berlin: 03-04-2012 12:43:38
date_default_timezone_set('Europe/Sofia');
dump('Sofia: '. date('d-m-Y H:i:s', $date)); // Sofia: 03-04-2012 13:43:38
dump function returns '<pre>'. $something .'</pre>';
UTC is the international time standard. It is similar to Greenwich Mean Time (GMT), except that UTC observes no daylight saving time (DST) and is based on a 24-hour clock. Zero (0) hours UTC is midnight GMT. The local 24-hour time convention is converted to UTC by adding or subtracting hours based on location in relation to the prime meridian, as well as local daylight saving time considerations.
First, make sure both time zones are same. Then, don't store in datatime format, use integer. Convert the date to timestamps and then store. Like
$time = time(); //get the current time stamp
//Now insert $time
Now, both places are in common ground, You may do as you like. Changing date among different timezone is rather easy.
echo gmdate("M d Y H:i:s", $time);

Convert PHP datetime to MySQL RFC-822 valid Date-Time for RSS Feed

I want to add a date/time, created in PHP, to MySQL that is valid in a RSS Feed.
I'm using in PHP
$d = date( 'Y-m-d H:i:s T', time() );
$mysqldate = gmdate(DATE_RSS, strtotime($d));
inserting that into a DATETIME field in my database
But it saves it in this format Wed, 02 Oct 2002 08:00:00
and it need to be in this format to be RFC-822 valid Wed, 02 Oct 2002 08:00:00 EST
Use DATE_RFC822 instead of DATE_RSS
Why are you converting a php date time to a string, then converting that string back into a datetime object again? that's a serious waste of cpu cycles. why not simply do
$mysqldate = gmdate(DATE_RSS, time())?
as well, gmdate generates a UTC timestamp, for which there is no timezone - it's always GMT+0
Answer is very simple just use this format:
<pubDate>'.date('r', strtotime($rss_row['your_date_field'])).'</pubDate>
The original echo is:
echo date('r', strtotime($my_date));
This turns the datetime from inside our MySQL table which is formatted like: YYYY-MM-DD HH:MM:SS and turns it into a UNIX string that represents the same date.
Once we do that to our date, we have the date() function’s many wonders at our disposal. Going into those many wonders is more than I’ll get into here, but I’ve posted about it here.
In this particular case, adding the ‘r’ parameter to the date() function does all the work of reformatting our UNIX string into our RSS feed date format.
It’s that easy.
When saving something into a MySQL DATETIME field, you can not specify the format. DATETIMEs are stored in an internal format that is only concerned with the time value, not with the formatting. You will always have to format the date the way you need it after (or while) retrieving it from the database:
date(DATE_RSS, strtotime($dateFromDatabase));
To insert a date into the database you just need to provide it in a format MySQL understands, it will then be converted to said internal format and the formatting will be lost:
sprintf("INSERT INTO `foo` (`date`) VALUES('%s')", date('Y-m-d H:i:s'))
date('r', strtotime($object->pubDate))
-works nice
Actually DATETIME fields don't save any information about the timezone (http://dev.mysql.com/doc/refman/5.1/en/datetime.html).
So you need to append the timezone AFTER fetching the date from the database.

Categories