zend locale is making me nervous: wrong datepresentation - php

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.

Related

Convert timestamp coming from SQL database to String

I am saving the timestamp in SQL as bigint(20). The number is correct and in android or https://www.epochconverter.com it works fine.
However I am not able to create a date-string based on the timestamp received from database.
First of all, the timestamp seems to come from database as a String, so I can't just say echo date("d.m.Y, $timestamp). The result is the famous 31.12.1969.
So I tried echo date("d.m.Y, strtotime($timestamp)). However, even though strtotime is said to be able to convert almost everything to a timestamp, a simple String containing a timestamp is not possible. Results still remained on the last day of Brian Adams probably favorite year.
Some progress I made by casting the $timestamp to a float value like so: echo date("d.m.Y", floatval($timestamp));. However, now things got really confusing for me. I seemed to have successfully converted my timestamp, however, date() gave me the dates around 02.09.52299.
The timestamps I am using are timestamps of current time, e.g. 1588489252657, which currently leads to the date 23.03.52307.
So all I want is to come to a date based on the timestamp 1588489252657 to see the 03.05.2020 on my screen.
Thanks for any advice!
<?php
$timestamp = 1588489252657; // Timestamp in Milliseconds
$seconds = round($timestamp/1000, 0); // Timestamp Rounded to Seconds
$date = new DateTime(); // Create PHP DateTime Object
$date->setTimestamp($seconds); // Set the Timestamp
echo $date->format('Y-m-d H:i:s'); // Specify the Required Format
The answers are pretty much in the comment sections. But I have shared this answer since this is another approach in OOP fashion. You can leverage the power of PHP's DateTime Class.
PHP Official Documentation For DateTime Class Link Below:
PHP DateTime Class
You have to transform the timestamp to seconds first.
$timestamp = 1588489252657;
$dateInUnixSeconds = round($timestamp / 1000, 0);
$date = \DateTimeImmutable::createFromFormat('U', (string) $dateInUnixSeconds);
echo $date->format('d.m.Y');
PS:
I recommend you to use the \DateTimeImmutable object to avoid mutability problems.
https://github.com/Chemaclass/php-best-practices/blob/master/technical-skills/immutability.md

Date from API call not being accepted in Laravel as a dateTime field

I am getting dates from an API call. The date is formatted in this way
2017-10-19T15:30:00
I want to store this date in my MYSQL database using Laravel Database Migration, currently I am using
$table->dateTime('datetime');
When I store it using a dateTime field as above, all I get is
0000-00-00 00:00:00
When I use a timestamp format, I don't get accurate dates, I just get the current time and date.
How can I solve this? Any help would be appreciated, and please let me know if you want further information.
Luckily, Laravel uses the Carbon class, which makes things a lot easier to modify dates. In your case, you want to do this:
Carbon::createFromFormat('Y-m-d\TH:i:s', $date);
There are two ways you can implement it: you can modify it before you save it to your database, or you can add a mutator on your model.
public function setDatetimeAttribute($value)
{
$this->attributes['datetime'] = Carbon::createFromFormat('Y-m-d\TH:i:s', $value);
}
You may want to build in some validation to see which format the date/time is in before you try to convert it.
in the model you should put:
protected $dates = ['datetime'];
Use Carbon
$dt = Carbon::parse('1975-05-21 22:23:00.123456');
to save:
$model = new Model;
$model->date = $dt; // you can use the carbon object directly
$model->save();

Modify an existing DateTime object using a string containing a timestamp in PHP

I've got a variable declared like such: $var = new DateTime(null);.
I want to change the time that echo $var->format('g:i A'); outputs.
I want to achieve this solely by using a time string such as 07:30:28.
How can I do this without re-creating a DateTime object ($var) each time? I can't think of a way to achieve this.
DateTime::modify() will do exactly what you want. It will quite happily accept a time in string format and apply it to the object:-
$date = new \DateTime();
$date->modify('07:30:28');
See it working.
Alternatively, you can do it all in one go:-
$date = (new \DateTime())->modify('07:30:28');

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

PHP: Need a opposite method of timezone_name_from_abbr?

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.

Categories