PHP: Need a opposite method of timezone_name_from_abbr? - php

I need an exactly opposite method of timezone_name_from_abbr(): http://php.net/manual/en/function.timezone-name-from-abbr.php
I have a list of timezones name like:
Australia/Brisbane
Australia/Hobart
Asia/Vladivostok
Australia/Lord_Howe
Asia/Magadan
Asia/Kolkata
America/Los_Angeles
......
I need method which will take timezone as a param and return me a Abbreviation of it. For example:
If I use method like:
$timeAbbr = timezone_abbr_from_name('America/Los_Angeles');
echo $timeAbbr;
Result should be:
PST

This should work.
function timezone_abbr_from_name($timezone_name){
$dateTime = new DateTime();
$dateTime->setTimeZone(new DateTimeZone($timezone_name));
return $dateTime->format('T');
}

DateTimeZone::ListAbbreviations will give you an associative array with all long names related to a specific abbreviation. It should be fairly straightforward to build a function with this that returns the correct abbreviation. There is nothing ready-made in the User Contributed Notes as far as I can see.

Related

Timezone formatting not returning abbreviation on certain timezones

I'm a bit confused as to why the date formatter T does not always return a timezone abbreviation.
The following code Carbon::now()->timezone('Europe/London')->format('T') returns 'BST', Carbon::now()->timezone('Europe/Stockholm')->format('T') returns 'CEST', but Carbon::now()->timezone('Asia/Bangkok')->format('T') returns '+07', which is rather confusing for the users of a scheduling system I'm building.
I would expect T to always return a 'non-numeric' indication of the timezone, is there a way to achieve this without having to resort to writing out 'Asia/Bangkok'?
It should return "ICT". It's a known bug of PHP: https://bugs.php.net/bug.php?id=74835
You get the same result without Carbon:
$date = new DateTime('now', new DateTimeZone('Asia/Bangkok'));
echo $date->format('T');

PHP DateTime constructor - date string format based on DateTimeZone

I have a multi national system that uses two different types of date formats. One uses "d-m-Y" the other uses "m-d-Y". I have a Local class that is responsible for creating a DateTime object based on a date string passed into it.
The string being passed in is dynamic and can be either version. The problem is that even if you specify the DateTimeZone in the DateTime constructor you still have to pass in a string based on 'm-d-y'.
I need to be able to pass a string to the DateTime constructor based on the DateTimeZone that is passed in along with it. For example, if my TimeZone is set to Australia/Sydney
the DateTime constructor should accept a string like '31/11/2017' but it doesn't. The DateTime constructor doesn't take into account the TimeZone passed in with the string. I would have to use DateTime::createFromFormat, but this means I would have to manually specify a format for hundreds of time zones. It would be much easier if the DateTime constructor would take a string format based on the time zone passed in like this...
$dateTime = new DateTime('31/11/2017', new DateTimeZone('Australia/Sydney'))
This should work but doesn't in my case. Does anyone know what I am doing wrong? There must be a way to achieve this.
Maybe the format for your date isn't accepted by PHP's DateTime constructor. For a workaround try this:
$dateTime = DateTime::createFromFormat('d/m/Y', '31/11/2017')
->setTimeZone('Australia/Sydney');
or
$dateTime = DateTime::createFromFormat('d/m/Y', '31/11/2017', 'Australia/Sydney');
you can use the php-intl-extension to get default strings per locale-string
foreach (["en_US", "en_IE", "de_DE"] as $fmt) {
$formatter = datefmt_create($fmt, IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
echo datefmt_get_pattern($formatter) . "\n";
}
see the documentation on datefmt_get_pattern for more details.

Is it possible to create a DateTimeZone from an offset?

The DateTimeZone constructor only accepts a region name:
new DateTimeZone('Europe/London');
And not an offset from UTC:
new DateTimeZone('+01:00'); // Unknown or bad timezone (+01:00)
However, it is possible to obtain such a DateTimeZone from a DateTime:
(new DateTime('2012-12-28T00:00:00+01:00'))->getTimezone()->getName(); // +01:00
So this is a bit weird. Is there a way to directly obtain a DateTimeZone from an offset?
In addition to RafaƂ's answer, the simplest way I've found so far is:
DateTime::createFromFormat('O', '+01:00')->getTimezone();
Edit
This was a bug that has been fixed in PHP 5.5.10. It now works!
Modern answer:
new DateTimeZone('+0100');
Documentation:
http://php.net/manual/en/datetimezone.construct.php
Check out this function.
http://pl1.php.net/manual/en/function.timezone-name-from-abbr.php
You'll need to convert hours to seconds and pass them as second parameter.
Sth. like new DateTimeZone(timezone_name_from_abbr('', 3600, 0)) should work.
I dont think that there is any predefined way you wanna go. But if you declare any global function that will return you date and time with the offset added, it might help you.
Example :
function getDateTime($format="dd-mm-YY"){
$currDate= date($format);
$currDate=date($format,strtotime("+1 day",$currDate); // or whatever needed instead of +1 day
}

PHP Zend date format

I want to input a timestamp in below format to the database.
yyyy-mm-dd hh:mm:ss
How can I get in above format?
When I use
$date = new Zend_Date();
it returns month dd, yyyy hh:mm:ss PM
I also use a JavaScript calender to insert a selected date and it returns in dd-mm-yyyy format
Now, I want to convert these both format into yyyy-mm-dd hh:mm:ss so can be inserted in database. Because date format not matching the database field format the date is not inserted and only filled with *00-00-00 00:00:00*
Thanks for answer
Not sure if this will help you, but try using:
// to show both date and time,
$date->get('YYYY-MM-dd HH:mm:ss');
// or, to show date only
$date->get('YYYY-MM-dd')
Technically, #stefgosselin gave the correct answer for Zend_Date, but Zend_Date is completely overkill for just getting the current time in a common format. Zend_Date is incredibly slow and cumbersome to use compared to PHP's native date related extensions. If you don't need translation or localisation in your Zend_Date output (and you apparently dont), stay away from it.
Use PHP's native date function for that, e.g.
echo date('Y-m-d H:i:s');
or DateTime procedural API
echo date_format(date_create(), 'Y-m-d H:i:s');
or DateTime Object API
$dateTime = new DateTime;
echo $dateTime->format('Y-m-d H:i:s');
Don't do the common mistake of using each and every component Zend Frameworks offers just because it offers it. There is absolutely no need to do that and in fact, if you can use a native PHP extension to achieve the same result with less or comparable effort, you are better off with the native solution.
Also, if you are going to save a date in your database, did you use any of the DateTime related columns in your database? Assuming you are using MySql, you could use a Timestamp column or an ISO8601 Date column.
This is how i did it:
abstract class App_Model_ModelAbstract extends Zend_Db_Table_Abstract
{
const DATE_FORMAT = 'yyyy-MM-dd';
public static function formatDate($date, $format = App_Model_ModelAbstract::DATE_FORMAT)
{
if (!$date instanceof Zend_Date && Zend_Date::isDate($date)) {
$date = new Zend_Date($date);
}
if ($date instanceof Zend_Date) {
return $date->get($format);
}
return $date;
}
}
this way you don't need to be concerned with whether or not its actually an instance of zend date, you can pass in a string or anything else that is a date.
a simple way to use Zend Date is to make specific function in its business objects that allows to parameter this function the date format. You can find a good example to this address http://www.pylejeune.fr/framework/utiliser-les-date-avec-zend_date/
this is i did it :
Zend_Date::now->toString('dd-MM-yyyy HH:mm:ss')
output from this format is "24-03-2012 13:02:01"
and you can modified your date format
I've always use $date->__toString('YYYY-MM-dd HH-mm-ss'); method in the past but today didn't work. I was getting the default output of 'Nov 1, 2013 12:19:23 PM'
So today I used $date->get('YYYY-MM-dd HH-mm-ss'); as mentioned above. Seems to have solved my problem.
You can find more information on this on output formats here: http://framework.zend.com/manual/1.12/en/zend.date.constants.html

zend locale is making me nervous: wrong datepresentation

First I had problems with getting date's into my db see here. Now I have problems with getting it into the database on the right format.
This is my code:
public function editAction()
{
if($this->_request->getParam('id')){
$id = $this->_request->getParam('id');
$data = $this->_evtObj->selectOneRow($id);
// initialize the form
//var_dump($data);
$form = new JS_Form_EventForm();
$array = $data->toArray();
//$locale = Zend_Registry::get('locale');
$locale = new Zend_Locale();
$date1 = new Zend_Date($locale);
$date1->set($array[0]['evt_startdate']);
$array[0]['evt_startdate'] = $date1->get();
$array[0]['evt_enddate'] = date('%d-%m-%Y',(string)$array[0]['evt_enddate']);
$form->populate($array[0]);
$this->view->form =$form;
}
As you can see it populates the form with dates from the db. In the db the date is saved like 2010-01-15. As you can see in the above example i tried out two things:
locale = new Zend_Locale();
$date1 = new Zend_Date($locale);
$date1->set($array[0]['evt_startdate']);
$array[0]['evt_startdate'] = $date1->get();
This shows the date like: '1262300400'
and:
$array[0]['evt_enddate'] = date('%d-%m-%Y',(string)$array[0]['evt_enddate']);
this shows the date like: '%01-%01-%1970'
I want the date to be shown like dd-mm-yyyy
How to deal with this? All this date business drives me mad.
I am running zf 1.9.6
any idea's?
I'd suggest using something like this
$date = new Zend_Date($array[0]['evt_startdate'],Zend_Date::DATES);
$array[0]['evt_startdate'] = $date1->toString('dd-MM-YYYY');
Documentation
Try date('d-m-Y', $array[0]['evt_enddate'])
Also, the second param to date should be a timestamp. I do not know what is inside that array you use, but it certainly does not need to be typecasted to string. If you want to create timestamp from a formatted date, use strftime().
If you use get() without any arguments, the timestamp is returned. If you want to get the date part with time from Zend_Date use getDate() instead of get(). That will set the time part to 00:00:00 and return it with the date. If you only want the date part use get() with the DATE_MEDIUM constant. If you just want to format from Zend_Date, use Peter Lindqvist's suggested answer below.
Opinion: Personally I'd suggest to avoid Zend_Date altogether. I have the impression it is akward to use and pretty slow compared to PHP's native DateTime and DateTimezone classes. I use Zend_Date only for localized formatting nowadays, because that's where it shines.

Categories