I am working with neo4j in PHP and I need to have a DateTime field that allows to store the time zone. If I save it as a string it is more difficult to make queries.
Add the timezone, and just output the string like this:
$x = new DateTime('2018-09-18 22:00:00', new DateTimeZone('Europe/Brussels'));
echo $x->format(DateTime::W3C);
Which gives you:
2018-09-18T22:00:00+02:00
When you pull your time from the DB, you can now create the object like this:
DateTime::createFromFormat(DateTime::W3C, $row['your_date_column']);
Play with it here: https://3v4l.org/DQjJO
Related
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
I have a file of raw text/xml information that lists events occurring on the current day. The start time for each event is expressed in 00:00:00 24-hour format and is based on the Europe/London timezone. What I want to do is convert each event start time found in the file so that it is expressed in 'g:i A' format and is based on the America/New_York timezone.
Playing around, the following code works just fine if I define the source string as a single instance:
//output will be 3:45 PM
$src_tm = '19:45:00';
$src_tz = new DateTimeZone('Europe/London');
$dest_tz = new DateTimeZone('America/New_York');
$tm = new DateTime($src_tm, $src_tz);
$tm->setTimeZone($dest_tz);
$dest_tm = $tm->format('g:i A');
echo $dest_dt;
However as I said above, I want to do this for each instance in the file. I've come up with the following regex to identify each instance: '/\d+:\d+:00/' but I am having extreme difficulty making things work using the regex with preg_replace and DateTime. What do I need to do to ensure that each start time in the file is identified and converted to 'g:i A' and America/New_York?
I would suggest not using regular expressions to manipulate the XML file. This could be error-prone.
Instead, look into something like SimpleXML for parsing the XML file into a object graph whose nodes you can query and manipulate safely. Once you are done updating the date formats and timezones in each of the relevant nodes, you can save the object graph back into the file as an XML string.
Matt was correct on UTC rather than Europe/London. Thank you for pointing it out. And yes, there is no need for assigning to a particular date in my case, as the information I am using is refreshed daily. So the default to the current date is all I need.
With that said, I was able to get things right after reading about preg_replace_callback. Worked a charm!
//adjust event start time for America/New York
$input = preg_replace_callback('/\\d{2}:\\d{2}:\\d{2}/', 'replace_timestamp', $info);
function replace_timestamp($matches)
{
$source_tz = new DateTimeZone('UTC');
$destination_tz = new DateTimeZone('America/New_York');
$time = new Datetime($matches[0], $source_tz);
$time->setTimeZone($destination_tz);
return $time->format('g:i A');
}
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');
So im trying to insert a time using an input text field into a database table with data type TIME.
The format of time that I want to insert should be like this:
H:MM pm// example: 6:30 pm
The problem is the am/pm doesnt insert in my database table.
Only the hour and minute.
Please give me idea how to solve this.
Better with sample codes. Thanks.
Data Type TIME is for storing time data type - that means no AM/PM. Store the data in Your database in 24 hour format and format it to 12 hour format with am/pm in PHP or MySQL using one of these:
PHP:
$date = new DateTime($mysql_column['time']);
$date->format('h:i:s a');
or:
$date = date('h:i:s a', strtotime($mysql_column['time']));
or MySQL:
SELECT DATE_FORMAT('%h:%i:%s %p', time) FROM table;
Store the TIME as a standard format (18:30:00), and the format it however you want when you display it (Using DateTime objects or the date functions).
MySQL doesn't support extra formats when storing time data.
I think you want to add the jquery time picker value in your database with actual format in the database.
Here I have written some function
function update_time($time){
$ap = $time[5].$time[6];
$ttt = explode(":", $time);
$th = $ttt['0'];
$tm = $ttt['1'];
if($ap=='pm' || $ap=='PM'){
$th+=12;
if($th==24){
$th = 12;
}
}
if($ap=='am' || $ap=='AM'){
if($th==12){
$th = '00';
}
}
$newtime = $th.":".$tm[0].$tm[1];
return $newtime;
}
$time = update_time($_POST['time']); //here I am calling the function now you can insert the value in db
you just have to call the function and insert the returned value in database.
And while printing that you can do something like that echo date("h:i A",strtotime($time));
Change the type of the field to a varchar. TIME cannot store it like that. However, keep in mind that storing it like you want to will make it more difficult to provide localized results if that is something you will eventually need. That is, timezone support becomes difficult if you are not storing the timestamp itself, but rather a user-friendly representation.
EDIT: Or, DATETIME works as well, as was pointed out in the comments above.
You can use the DateTime Object in PHP which has functions to create a time object from any format and also has a function to output a time in any format like so
<?php
$date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');
?>
http://php.net/manual/en/datetime.createfromformat.php
You would be best changing the field type to 'VARCHAR (32)', and then writing the time with PHP.
Example: date('m/d/y g:i:sa');
Why do you want to store the am or pm anyhow? If you store the date/time as a unix epoch timestamp, you can format the date however you want in the program - not the database.
Example: time(); - Store this in an INT(8) field.
date('m/d/y g:i:sa, $time()); - Output from DB like this.
try .ToShortTimeString() after your date variable.
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.