PHP datetime format() incorrect date - php

I have a PHP datetime object that I have been trying to convert into a string with DateTime::format() . But this keeps giving me a wrong date . For some reason I keep getting a date that is one day prior the day that I am running my code no matter what value I give the date.
My DateTime object -
object(DateTime) {
date => '2017-03-25 00:00:00'
timezone_type => (int) 3
timezone => 'UTC'
}
I use this to format the DateTime into a string -
$myDateObject->format('Y/m/d')
Gives me -
2017/03/23
There is absolutely no code between the line that prints the DateTime object and the line that formats the object ie there are no modifications made on the object .
If it helps the output of my server's date -u returns Fri Mar 24 06:08:39 UTC 2017 . Also if I create the date string with hours and minutes using $myDateObject->format('Y/m/d h:i') I get 2017/03/23 12:00
EDIT
The output of my date_default_timezone_get() is UTC
date('Y-m-d') gives 2017-03-24 ie today's date

Check out default time zone set in PHP
you may wanna try setting default time zone example: date_default_timezone_set('America/Toronto');

Related

DateTime converts wrong when system time is 30 March

Assume system time is set to 2017-03-30. Then this code will convert the date wrong:
<?php
$dateTime = DateTime::createFromFormat('m-Y', '02-2017');
$converted = $dateTime->format('Y-m');
print_r($converted);
The value of $converted is
2017-03
but only when run from the browser. Run from command line, it gives the correct result 2017-02.
Anyone knows why? February does not have 30 days, so that might be a reason, but still.
Edit: Changed format from 'Y-m-d' to 'Y-m'.
Edit 2: Added information about command line vs browser.
The rules used by DateTime::__construct(), DateTime::createFromFormat() and strtotime() to parse various date & time formats and the values it uses to fill missing components are explained in the documentation.
When it parses an incomplete date, it uses the values from the current date and time for the missing components.
In your specific case, 02-2017 is converted to "February 2017" using the current day of month (30) for the missing day of month. I.e. 30 February 2017 that is then normalized to 2 March 2017.
You can tell DateTime::createFromFormat() to initialize all the components to the Unix epoch (instead of the current date & time) by placing an exclamation mark (!) in the format string:
$dateTime = DateTime::createFromFormat('!m-Y', '02-2017');
print_r($dateTime);
It outputs:
DateTime Object
(
[date] => 2017-02-01 00:00:00.000000
[timezone_type] => 3
[timezone] => UTC
)
What you have here is over-run. The process goes like this:
1) You give the dateTime object a formatted date, but without a day.
2) The dateTime object then can not use null days so instead uses todays date.
3) You state in your question that todays date is 2017-03-30 therefore to apply this to the given date value of 02-2017 would make:
30-02-2017
4) This is obviously not valid so the dateTime object over-runs this value and turns it into 02-03-2017.
You reqest an output format of Year - Month which gives you 2017-03.
Solution:
Always set a day value in your dates.

getTimestamp is not giving the correct hour

I have this PHP code:
$from_date = new DateTime('April-22-2016');
$from_date->format( 'Y-m-d 00:00:00' );
$from_date->setTime(0,0,0);
print ' / '. $from_date_unix = $from_date->getTimestamp();
The above code prints a Unix timestamp of 1461356160, which means
GMT: Fri, 22 Apr 2016 20:16:00 GMT
The hours are 20:16:00 - which is strange, since I already set the time to 00:00:00 via
$from_date->setTime(0,0,0);
Is my code wrong? Do I need to check something in php.ini?
The date you provided as first argument to DateTime::__construct() does not use any of the standard date and time formats understood by PHP. Therefore, it tries to identify the date and time components in the string you provided.
A print_r($from_date) immediately after it was created reveals what PHP (mis-)understood from your date:
DateTime Object
(
[date] => 2016-04-22 00:00:00.000000
[timezone_type] => 1
[timezone] => -20:16
)
Before anything else, when it starts parsing a string for date & time, PHP initialize the new DateTime object with the current date, time and timezone. Then it overwrites the components it identifies in your string as follows:
April was correctly identified as the month name;
22 is the day of the month;
for some reason I don't know now, it set the time of the new object to 00:00:00;
the rest of the string (-2016) was used as timezone offset; i.e. -20:16 hours.
Maybe the way it works sounds silly to you but since you provided it a random string, this is the best it could get out of it.
The next line of your code ($from_date->format( 'Y-m-d 00:00:00' );) produces a string and doesn't modify the DateTime object. Because you don't do anything with the string returned by DateTime::format(), the entire line is a no-op.
The next line ($from_date->setTime(0,0,0);) also doesn't have any effect on $from_date because it's time already is 00:00:00.
Now it's clear why $from_date->getTimestamp() returns the time 20:16 GMT: when it's 00:00 at the timezone with offset -20:16, on the GMT timezone there already is 20:16.
In order to get what you want you need to use the DateTime::createFromFormat() static function:
$from_date = DateTime::createFromFormat(
'!F-d-Y',
'April-22-2016',
new DateTimeZone('GMT')
);
print ' / '. $from_date_unix = $from_date->getTimestamp();
Remark the exclamation mark (!) at the start of the format specifier. It tells PHP to reset all the date and time components to the Unix Epoch. This way the generated date already has the time 00:00:00 and there is no need to set it.
Its output is:
1461283200
You can parse the DateTime object with the right format with DateTime::createFromFormat
Use it like this:
$from_date = DateTime::createFromFormat('!F-d-Y', 'April-22-2016');
$from_date->format( 'Y-m-d 00:00:00' );
print ' / '. $from_date_unix = $from_date->getTimestamp();

PHP date timestamp timezone not converted properly

So I have this code:
$timestamp = 1414708099;
echo $timestamp;
$date = date_make_date($timestamp, 'UTC', 'datestamp');
date_timezone_set($date, timezone_open('America/New_York'));
$timestamp = $date->format('U');
echo '<br>';
echo $timestamp;
which is supposed to convert the timezone of the initial timestamp from UTC to new york.
but then this ends up printing
1414708099<br>1414708099
hence the timezone didnt change...
what did I do wrong?
btw it also uses Drupal 6 date_api.module: http://drupalcontrib.org/api/drupal/contributions!date!date_api.module/function/date_make_date/6
As per comments
A timestamp is always UTC. You can't apply a time zone to a timestamp - consider its timezone as 0. Whatever you do, it stays 0. You asked for a date formatted with U - manual states this:
U: Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
You can't get seconds from Unix Epoch for New York. That number is the same for any location in the world.
Now, had you formatted that date using, say, $date->format('Y-m-d H:i:s') then you would get correctly formatted time with the timezone offset for New York.
Long story short - there is no problem whatsoever here. It all works as intended.

What date format is this in? (PHP Codeigniter File Helper)

I'm trying to work out what format this date is in!
'date' => int 1342640973
Date today is 18.07.2012
I got it from the get_file_info function in the CI File Helper.
It's a unix timestamp, which is the number of seconds that have elapsed since midnight Coordinated Universal Time (UTC), January 1, 1970, not counting leap seconds.
To get the current timestamp in PHP, you can use time and to convert a timestamp into a human-readable format you can use date.
It's a unix timestamp!
The value you have represent a date/time in seconds since the first of January 1970 (in UTC), it's often referred to as a "unix timestamp" because of it's origin.
Handling this time representation is easily done in PHP, there are native functions made to convert back and to the format.
time () will return the current time in the format specified (unix timestamp), to convert this into a readable string you can use date with the appropriate format-string, as in the below example:
$unix_timestamp = 1342640973;
$now_utimestamp = time ();
print_r (
array (
date ("Y-m-d G:i:s", $unix_timestamp),
date ("Y-m-d G:i:s", $now_utimestamp)
)
);
output on my system:
Array
(
[0] => 2012-07-18 21:49:33
[1] => 2012-07-18 22:18:43
)
Unless you have told PHP which timezone it's currently in (using php.ini or equivalent) you'll need to specify this using the function date_default_timezone_set(), passing it the value of date_default_timezone_get() will try to set it according to your system preferences.
If it's unable to find a correct match UTC will be used per default.
in codeigniter use
unix_to_human(TIMESTAMP)
to get the human readable date, it will require to include date helper

Convert time to readable format

I have time like this in the database
[open_time] => 10:00:00
[close_time] => 23:00:00
I want to convert it into readable form like 10:00am 11:00pm
I tried this:
$open = date("g:s a",$time['open_time']);
$close = date("g:sa",$time['close_time']);
I'm getting the following error:
A non well formed numeric value encountered
date expects an integer argument, the traditional Unix timestamp.
Try this:
date('g:s a', strtotime($time['open_time']));
strtotime attempts to convert a string into an integer Unix timestamp as expected by date.
If it's in your database, consider using the MySQL DATE_FORMAT() function directly in your request
The second argument needs a UNIX timestamp (epoch time):
http://php.net/manual/en/function.date.php
timestamp
The optional timestamp
parameter is an integer Unix timestamp
that defaults to the current local
time if a timestamp is not given. In
other words, it defaults to the value
of time().
<?php
$t = time();
print_r($t);
print_r(date('g:i a', $t));
?>
gives
1288935001
10:30 pm

Categories