How to translate AM and PM in PHP date - php

I have a context in a forum settings that use date function to handle datetime string. This context accept the format string of the date function. However, the forum in the Arabic language and I want to translate the string of am and pm to another equivalent in an Arabic string such as ص and م respectively. I tried the following code to make the external (the context) date() to replace:
echo date("addslashes(date('D d M Y g:i'),'A..Z')".str_ireplace(array('pm','am'), array('م','ص'),date(' a')));
I used addslashes in hope to escape the output of the first inner date. However the output is something like that:
pm202005Sundaypm0509UTC05(20pm30UTC('Sun 20 Apr 2014 9:03'),'PM..0') م
It is just scceeded in replacing am and pm but the whole date string is missy as you see. This is a live demo of the code. I need to know does it possible to get what I need, assuming that any code will be done inside a predefined date()?

You can use a ternary operator inside the date to set a conditional format.
date($format = (date(G) > 11) ? 'h:i \ص' : 'h:i \م');
or for am/pm
date($format = (date(G) > 11) ? 'h:i \p\m' : 'h:i \a\m');
You can set the format different than h:i but this will show 05:40 pm for 17:40 or 05:40 am for 05:40. It looks for date(G) which is the hours in 0-23 format. If date(G) is greater than 11, it uses the first format, else uses the second format.
Here is a fork of your code http://ideone.com/BobelH

There is another approach. It uses strtotime and str_replace as follows:
<?php
$dtFormat = "Y-m-d H:i:s"; //MySQL Datetime format
$curDT = date($dtFormat);
$curTime = strtotime($curDT);
$nowFormat = "Y-m-d h:i:s ";
$arrEn = array('am', 'pm');
$arrAr = array('ص', 'م');
echo date($nowFormat).str_replace($arrEn, $arrAr,date("a", $curTime));
A working demo: http://ideone.com/xfECCD

Related

How to convert MySQL TIMESTAMP to date time in PHP

I have a MySQL DB table with a column named "timestamp", a type of timestamp, and attribute of on update CURRENT_TIMESTAMP and a default of CURRENT_TIMESTAMP.
If I add a record to the table, specifying other values, but not the timestamp, then the timestamp is automatically added like 2016-12-28 17:02:26.
In PHP I query the table using the following query
SELECT * FROM history WHERE user_id = 9 ORDER BY timestamp ASC
The result of the query is saved into $rows and I use a foreach to create an array with some of the other values formatted. I am attempting to format the time stamp to UK type 24-hour date time: dd/mm/yy, HH:MM:SS.
I have tried both the date() and strftime() functions as follows:
$formatted_datetime = strftime("%d %m %y %H %M %S", $row["timestamp"]);
$formatted_datetime = date("d/m/y, H:i:s", $row["timestamp"]);
Both of these result in the following notice and the date time being output incorrectly like 01 01 70 00 33 36:
Notice: A non well formed numeric value encountered in /home/ubuntu/workspace/pset7/public/history.php on line 20
I am new to PHP and MySQL and so far none of the other questions or documentation I have seen have successfully addressed performing this conversion.I do not understand why strftime() does not work, nor how to do this properly?
To do this the OO (and most flexible) way use DateTime class and use the static createFromFormat method to instantiate a new DateTime object:
$new_datetime = DateTime::createFromFormat ( "Y-m-d H:i:s", $row["timestamp"] );
Now you can use the $new_datetime object to generate any string representation you'd like by calling the object's format method:
echo $new_datetime->format('d/m/y, H:i:s');
To boot, you since you've a DateTime object you can now also to any manner of transformation (like shifting timezones or adding days), comparison (greater or less than another DateTime), and various time calculations (how many days/months/etc... between this and another DateTime).
DateTime:http://php.net/manual/en/class.datetime.php
Learn it. Love it. Live it.
Normally in MySQL date timestamp save time as YYYY-MM-DD HH:MM:SS (2016-12-20 18:36:14) formate you can easily convert them as your wish using date formate but have to convert your input to time first. Following will do the trick
$formatted_datetime = date("d/m/y, H:i:s", strtotime($row["timestamp"]));
Why not make MySQL do the work? And do you really want mm/dd/yy, not dd/mm/yy?
SELECT *, DATE_FORMAT(timestamp, '%m/%d/%y, %T') formatted_date FROM ....
Then you can extract the formatted date as $row['formatted_date'].
See https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
The date is of timestamp type which has the following format: ‘YYYY-MM-DD HH:MM:SS’ or ‘2008-10-05 21:34:02.’
$res = mysql_query("SELECT date FROM times;");
while ( $row = mysql_fetch_array($res) ) {
echo $row['date'] . "
";
}
The PHP strtotime function parses the MySQL timestamp into a Unix timestamp which can be utilized for further parsing or formatting in the PHP date function.
Here are some other sample date output formats that may be of practical use:
echo date("F j, Y g:i a", strtotime($row["date"])); // October 5, 2008 9:34 pm
echo date("m.d.y", strtotime($row["date"])); // 10.05.08
echo date("j, n, Y", strtotime($row["date"])); // 5, 10, 2008
echo date("Ymd", strtotime($row["date"])); // 20081005
echo date('\i\t \i\s \t\h\e jS \d\a\y.', strtotime($row["date"])); // It is the 5th day.
echo date("D M j G:i:s T Y", strtotime($row["date"])); // Sun Oct 5 21:34:02 PST 2008
I would use the Carbon class and its String Formatting
$carbon = Carbon::instance('2016-12-28 17:02:26');
Then you can format it the way you want.

Datetime creates blank result

Well, I have this code here
$rowValue[$y] = '16/08/2013';
$replaceThis = array("/");
$rowValue[$y] = str_replace($replaceThis, "-", $rowValue[$y]);
this will produce an output with string datatype, '16-08-2013'
and when I try to do this
$rowValue[$y] = DateTime::createFromFormat('d-M-Y H:i:s e', $rowValue[$y]);
echo $rowValue[$y];
it doesn't work, or simply it just displays blank...
You're doing it incorrectly you need to give your current/passed date format to createFromFormat method (i.e Y-m-d in your case) and than after creating DateTime object you can format it using format method.
$rowValue[$y] = DateTime::createFromFormat('d-m-Y', $rowValue[$y]);
echo $rowValue[$y]->format('d-M-Y H:i:s e');
DEMO.
Check the DateTime format you're using. From the docs:
http://www.php.net//manual/en/datetime.createfromformat.php
'M' is used for "a textual representation of a month, such as January or Sept." You need to use 'm' or 'n' instead, which is used for a "numeric representation of a month, with or without leading zeros." Since your string representation has a leading 0, you'll want 'm'.
Your code should look like the following:
$rowValue[$y] = DateTime::createFromFormat('d-m-Y H:i:s e', $rowValue[$y]);
I don't understand why ''d-M-Y H:i:s e' doesn't work.. but thanks, it's now working. Still 3 mins til I accept your answer tho
it does not work because your string does not have time. You must supply the current format of your string which is "d-m-Y" in DateTime::createFromFormat().

Decoding date from integer in PHP

In PHP, I'm saving a date record as string in order to make conditions like "more than", "less than"; but I would really like to know how to decode it. What I want to do is something like this:
The moment that record is being saved is 2014, 08/06 1:30 in 24-hours format, so my integer should be like 201408060130, of course for this I use date() function.
But when it comes to decoding it to show it back like 2014, 08/06 1:30 or another format like 08/06 2014, 1:30 I really get stuck thinking on any solution for this.
I thought it would be like:
$date = date('YdmHm'); //Saving as 201408060130
$this->saveToDatabase($save, $mytable);
$dateDecoded = $this->getFromDatabase($mytable, $id, $theDateInteger);
$result = Date::getFormat($dateDecoded, 'YdmHm'); //Decode date format
echo $result->date('Y d/m, H:m'); //Show 2014 08/06, 1:30
This is simple & works. Just use strtotime:
$test_value = '201408060130';
echo date('Y d/m, H:i', strtotime($test_value));
The output is:
2014 06/08, 01:30
PHP has a really useful method under the Date class for this called DateTime::createFromFormat()
Here is an example usage:
$datetime = DateTime::createFromFormat('YdmHm', (string)$theDateInteger);
Now this is a valid datetime object which you can save to any formatting in a string if desired. For example:
echo $datetime->date('Y d/m, H:m');

Date conversion and updating mongodb document using PHP

Progress :
1. I retireved date from a collection.
Example format : Fri Oct 05 14:59:31 +0000 2012
2. I was able to change its format.
CODE USED :
$cur=$col->find(array(),array("created_at"=>1,"_id"=>0));
// created_at = contains Date value
$cur_all=$col->find();
while($doc=$cur_all->getNext())
{
$doc2=$cur->getNext();
$pieces = implode(" ", $doc2);
//converted the array to string with space delimiting
if($pieces!=NULL)
{
$date1 = date_create_from_format("D M d G:i:s +O Y", $pieces);
echo date_format ( $date1 , 'Y-m-d G:i:s' );
//This is the format i would like to update in mongodb..
$filter = array('_id'=>new MongoId($doc['_id']));
$update = array('$set'=>array('created_at'=> newMongoDate($date2)));
$col->update($filter,$update);
}
}
QUESTION :
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
P.S : I did a lot of research on Stackoverflow (And other places, as well.) but I could not come to any conclusions. That is why this question. Let me know if there are any clarifications
Hmm even though you have explained your background well your actual question:
Where to create a date object so that it could be updated to the documents in the collection in the expected format? (format : Y-m-d G:i:s )
Is a bit confusing.
MongoDB will always save the date in one format and one format only when using ISODate: http://en.wikipedia.org/wiki/ISO_8601 (otherwise known as MongoDate in PHP) and it is probably best to not mess with this status quo.
So I would recommend you use the format Y-m-d G:i:s only as display, i.e.:
$date1 = new MongoDate();
var_dump(date('Y-m-d G:i:s', $date1->sec));
And you use the original $date1 object to actually save to the database.
Of course this would change if you were to create a date in your specified format however here is a piece of code for an example:
$date1 = new MongoDate();
$date2 = new MongoDate(strtotime(date ( 'Y-m-d G:i:s', $date1->sec )));
var_dump(date('Y-m-d G:i:s', $date2->sec));
You can use the $date2 as the date to save into MongoDB formed from the specific format you want.
look at http://php.net/manual/en/class.mongodate.php
your code should create a date using a unix timestamp
$date2 = ('23rd April 2013');
$update = array('$set'=>array(
'created_at'=> new MongoDate(strtotime($date2))
));
http://www.php.net/manual/en/function.strtotime.php

Convert day numbers to string in wordpress

So I have the date like this in wordpress, I get it from a custom metabox where is stored like this, 23/02/2012, now how can I set wp_locale in WP or something like that, and I need to convert the date to: Monday 23 February 2012, but I need also to set the language, thats why I need that wp_locale because that output will be in Dutch.Thank you
The date format can be converted with the code below as a guide.
date('l j F Y', strtotime(str_replace('/', '-', '23/02/2012')))
The str_replace is necessary because with / PHP assumes m/d/y American date format, not the European d/m/y.
As for doing this in Wordpress with i18n support, you might consider http://codex.wordpress.org/Function_Reference/date_i18n
date_i18n('l j F Y', strtotime(str_replace('/', '-', '23/02/2012')))
I guess there are other ways to do this, but I'd do it as follows:
Upon 'save_post':
$date = explode ('/',$_POST["date_field"]);
$date = $date[1].'/'.$date[0].'/'.$date[2]; // dd/mm/yyyy to mm/dd/yyyy
$s = strtotime($date); /* UNIX TIMESTAMP */
and then store the Unix timestamp in the database.
Upon 'amdin_init' you'll need to do the exact opposite to load the date in the right format in the metabox:
global $post;
$custom = get_post_custom($post->ID);
if ($custom["date_field"][0]) {
$d = date("d/m/Y",$custom["date_field"][0]); // convert unix timestamp
} else {
$d = "";
}
And in your template file, use php functions setlocale and strftime to display the date:
$custom = get_post_custom($post->ID);
$d = $custom["date_field"][0];
setlocale(LC_TIME, 'nl_NL');
$s = strftime('%#d %B %Y',$s);
This should output something like 13 January 2012.

Categories