Wordpress date format - php

Is it possible to use some constant strings in date formatting in Wordpress?
something like:
year:Y, month:F
which would translate to:
year:2012, month:February

Yes that's possible. Wordpress uses the php: date-function to format the date, thus you can use the following format on the general settings page of your blog.
To use constant string you will need to escape every character that should not be parsed as part of the date:
\y\e\a\r: Y, \m\o\n\t\h: F
This formatting string will result in "year: 2013, month: February".
See also the Wordpress Codex on formatting date and time.

Related

PHP Date Formatting not working wen using date_format()

I have a date field I'm pulling from WordPress, where the default format is:
16/12/2016
Been a while since I played with PHP, but I remember the way to format dates was: echo date_format($date,"[format syntax]");
But when I do
$date = myWPField;
echo date_format($date,"F d, y");
If doesn't display the date.
What am I missing. Has this changed?
Since your date is not an acceptable format in date_create like mm/dd/yy(yy) or mm-dd-yy(yy)
Use php DateTime::createFromFormat function instead this function can detect what format you
(PHP 5 >= 5.3.0, PHP 7)
DateTime::createFromFormat -- date_create_from_format — Parses a time string according to a specified format
$date = '16/12/2016';
$show_date = DateTime::createFromFormat('d/m/Y', $date)->format('F d, y');
Demo
when create data format form string use slash format, it's in the mm/dd/yy(yy) format. So in you code your first 16 is not allowed by default, you have to specify in what format to create from the string.
Note that when you create a new date object using a format with slashes and dashes (eg 02-02-2012 or 02/02/2012) it must be in the mm/dd/yy(yy) or mm-dd-yy(yy) format (rather than british format dd/mm/yy)! Months always before years (the american style) otherwise you'll get an incorrect date and may get an error like the one above (where PHP is crashing on trying to decode a 13th month).

PHP mktime notice

I want to change given date and time or date only into Unix time.
I tried like this:
mktime("Jan-12-2012 2:12pm");
But it’s not working:
Even in PHP documentation I looked at many examples and many of them don’t consist the matter that I want.
And when I try:
$user_birthday=$_POST["user_birthday"];
$db_user_birthday=empty($user_birthday)?"":mktime($user_birthday);
$_POST["user_birthday"] was given value from form that is jan-12-2012 2:12pm
it show error like this:
Notice: A non well formed numeric value encountered in C:\Program
Files (x86)\Ampps\www\admin\index.php on line 76
How do I fix it or display time into Unix?
Use this one:
date("M-d-Y h:i:s", strtotime($user_birthday));
You should be using strtotime instead of mktime:
Parse about any English textual datetime description into a Unix
timestamp.
So your code would be this:
$user_birthday = $_POST["user_birthday"];
$db_user_birthday = empty($user_birthday) ? "" : strtotime($user_birthday);
Then you can process that date like this to get it formatted as you want it to:
echo date("M-d-Y h:ia", $db_user_birthday);
So your full code would be this:
$user_birthday = $_POST["user_birthday"];
$db_user_birthday = empty($user_birthday) ? "" : strtotime($user_birthday);
echo date("M-d-Y h:ia", $db_user_birthday);
Note I also added spaces to your code in key points. The code will work without the spaces, but for readability & formatting, you should always opt to use cleaner code like this.
You should take a look at this answer: convert date to unixtime php
Essentially, you have mixed up mktime() with strtotime(). strtotime() allows you to parse an English textual string into a Unix timestamp. mktime() constructs a unix datetime based on integer arguments.
For example (again taken from the question above)
echo mktime(23, 24, 0, 11, 3, 2009);
1257290640
echo strtotime("2009-11-03 11:24:00PM");
1257290640

How to format an UTC date to use the Z (Zulu) zone designator in php?

I need to display and handle UTC dates in the following format:
2013-06-28T22:15:00Z
As this format is part of the ISO8601 standard I have no trouble creating DateTime objects from strings like the one above. However I can't find a clean way (meaning no string manipulations like substr and replace, etc.) to present my DateTime object in the desired format. I tried to tweak the server and php datetime settings, with little success. I always get:
$date->format(DateTime::ISO8601); // gives 2013-06-28T22:15:00+00:00
Is there any date format or configuration setting that will give me the desired string? Or I'll have to append the 'Z' manually to a custom time format?
No, there is no special constant for the desired format. I would use:
$date->format('Y-m-d\TH:i:s\Z');
But you will have to make sure that the times you are using are really UTC to avoid interpretation errors in your application.
If you are using Carbon then the method is:
echo $dt->toIso8601ZuluString();
// 2019-02-01T03:45:27Z
In PHP 8 the format character p was added:
$timestamp = new DateTimeImmutable('2013-06-28T22:15:00Z');
echo $timestamp->format('Y-m-d\TH:i:sp');
// 2013-06-28T22:15:00Z
In order to get the UTC date in the desired format, you can use something like this:
gmdate('Y-m-d\TH:i:s\Z', $date->format('U'));
To do this with the object-oriented style date object you need to first set the timezone to UTC, and then output the date:
function dateTo8601Zulu(\DateTimeInterface $date):string {
return (clone $date)
->setTimezone(new \DateTimeZone('UTC'))
->format('Y-m-d\TH:i:s\Z');
}
Edit: clone object before changing timezone.
Since PHP 7.2 DateTimeInterface::ATOM was introduced in favor of DateTimeInterface::ISO8601, although it still lives on for backward compatability reasons.
Usage
$dateTimeObject->format(DateTimeInterface::ATOM)

How to format a PHP date in .Net DataContractJsonSerializer format?

There is a requirement to send a date inside a JSON post using PHP in this following format
\/Date(410256000000-0800)\/
How do I convert a standard dd-mm-yyyy h:i:s datetime like 01-01-2013 12:00:00 to that format in PHP? Just need to know what values correspond to what in that format, not really look for a stringify things answer.
This should do it:
$dateTime = DateTime::createFromFormat('d-m-Y H:i:s', '01-01-2013 12:00:00');
$requiredJsonFormat = sprintf(
'\/Date(%s%s)\/',
$dateTime->format('U') * 1000,
$dateTime->format('O')
);
echo $requiredJsonFormat; // prints '\/Date(1357038000000+0100)\/'
I leave it up to you to find what the formats U and O do from http://php.net/date.
An alternative would be to use PHP's DOTNET API and use the DataContractJsonSerializer class directly from PHP. However, you'd need .NET installed on the server and using PHP's DOTNET API is rather arcane.
The more interesting part is why you need this format at all. This is explained in a blogpost at http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx
But because of a strange oversight in the EcmaScript specs, there is no standard way of describing dates in JSON. […] Our current approach is using a small loophole in the JSON specs. In a JSON string literal, you may (or may not) escape some characters. Among those characters, weirdly enough, there is the slash character ('/'). […] The new format is "/Date(1198908717056)/" where the number is again the number of milliseconds since January 1st 1970 UTC […] The point is that this disambiguates a date literal from a string that looks like the same date literal, while remaining pure JSON that will be parsed by any standard JSON parser. Of course, a parser that doesn't know about this convention will just see a string, but parsers that do will be able to parse those as dates without a risk for false positives
We created a package for this: https://github.com/webapix/dot-net-json-date-formatter
It uses a similar approach than the previous answer, tested on PHP versions >= 5.6.
use DateTime;
use DateTimeZone;
use Webapix\DotNetJsonDate\Date;
$date = DateTime::createFromFormat(
'd-m-Y H:i:s',
'01-01-2013 12:00:00',
new DateTimeZone('+0000')
);
Date::toJsonDate($date); // returns '/Date(1357041600000+0000)/'

PHP Spreadsheet_Excel_Reader always reading date as Nov 30, 1999

I am using Spreadsheet_Excel_Reader to read .xls files in PHP.
Everything goes fine until it comes to reading a date. If I am reading a date field, it will always return the date as Nov 30, 1999 (or variations of this date depending upon the format). I have tried setting the OutputEncoding and it's giving the same result. I tried dumping the 'example.xls' that comes with the library and that also produces the same result.
Any help on a workaround for this would be highly appreciated.
You don't need to format your date in excel...if you have a date format in mind wrap it with double quote. e.g "13/04/1987" format("DD/MM/YYYY");
Spreadsheet_Excel_Reader will read this as a normal string with the double quote wrapper around it.
Then in your PHP make a query to remove and replace double quote with nothing.
$var = "13/04/1987";
$removeQuote = str_replace('"','',$var);
After this you will have to replace every occurence of the forwardslash (/) with hypen(-).
$removeSlashes = str_replace('/','-',$removeQuote);
Then use the date function in PHP to format it to your suitability.
$format = date('Y-m-d', strtotime($removeSlashes));
echo $format;
And you'r done... full code goes below.
$var = "13/04/1987";
echo date('Y-m-d',strtotime(str_replace('/','-',str_replace('"','',$var))));

Categories