I have PHP times for the start and end times of an event. This is a simple <?php time(); ?> for some future date's start and end time. I was wondering if anyone knew of a way to take either the numerical format (PHP time()) or taking some string value representing that time (I could do a strtotime($sometimevalue);) and turn it into the required Google Calendar time format.
Enough talking - here is an example of the time format:
20150107T003000Z/20150107T023000Z
This equates to January 6th, 2015 at 5:30 PM to January 6th, 2015 at 7:30PM.
So can someone explain to me how to translate a time() to this format?
Try this:
date_default_timezone_set('UTC');
$date = date("Ymd\THis\Z");
The first line sets the default timezone to use to be UTC (this is the "Z" at the end of the formatted time: Z = "Zulu Time"). I did this since I don't know if Google is expecting a UTC time or not. If you can use other timezones, then you can use one of the other timezone formats available.
In the next line, I use date to format the current Unix timestamp (when no timestamp is passed to date it defaults to the current time - i.e. time()). I'll break it apart for you:
Y - The four-digit year
m - The two-digit (including leading zero, if necessary) month
d - The two-digit (including leading zero, if necessary) day of the month
\T - The literal character T, which is a delimiter identifying that the time portion of the date is beginning. The slash is to escape the T, as it is otherwise used to display the timezone abbreviation (e.g. "PST")
H - The two-digit (including leading zero, if necessary) hour
i - The two-digit (including leading zero, if necessary) minute
s - The two-digit (including leading zero, if necessary) second
\Z - The literal character Z, indicating zulu time as discussed above. The slash is to escape the T, as it is otherwise used to display the timezone in seconds from UTC.
For reference, and to be sure I interpreted the question accurately, this code:
date_default_timezone_set('UTC');
echo date("Ymd\THis\Z", time());
Currently displays this result:
20110415T014623Z
I should note that you could also use gmdate() in place of date() and eliminate the need for the date_default_timezone_set() call, since gmdate() returns the result in GMT. I only hesitate to mention this because I've never been 100% clear on the difference, if any, between GMT and UTC, especially with other timezones/periods like BST (British Summer Time) and how they alter GMT, if at all. If someone could clarify this in the comments, I would be most appreciative.
Working solution taken from http://php.net/manual/en/function.date.php
Credit goes to Boris Korobkov.
// boris at psyonline dot ru 14-Jun-2007 03:05
<?php
/**
* Get date in RFC3339
* For example used in XML/Atom
*
* #param integer $timestamp
* #return string date in RFC3339
* #author Boris Korobkov
*/
function date3339($timestamp=0) {
if (!$timestamp) {
$timestamp = time();
}
$date = date('Y-m-d\TH:i:s', $timestamp);
$matches = array();
if (preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $timestamp), $matches)) {
$date .= $matches[1].$matches[2].':'.$matches[3];
} else {
$date .= 'Z';
}
return $date;
}
?>
Background:
From
http://www.ibm.com/developerworks/opensource/library/os-php-xpath/
I saw
"The published and updated elements use the RFC 3339 time-stamp format. "
And figured I ought google "rfc3339 PHP" to find a function that implements this format
It's little bit old but Google expects to get time in a ISO 8601. Example :
$objDateTime = new DateTime('NOW');
$isoDate = $objDateTime->format(DateTime::ISO8601);
SOURCE
The easiest way I use:
$postBody = new Google_Service_Calendar_Event(array(
.......
'start' => array(
'dateTime' => date_format($event_Start_datetime,'c');
........
//'c' - formats DateTime object as needed for Google Calendar
Related
I have a xml file, containing several dates, in this format: 2016-07-23T07:00:00.000Z. I'm using a php function to convert this in to a format for publishing on a website. This should actually result in something like Saturday, 24th of July (24th, not 23rd, because of the time offset. My function somehow ignores the T07:00:00.000Z part and thus returns Friday, 23rd of July. Can anybody help me out with the proper way to convert this date?
Thanks, Peter
The string in question
2016-07-23T07:00:00.000Z
is a W3C datetime format (W3C DTF) (Complete date plus hours, minutes, seconds and a decimal fraction of a second) which can be properly parsed incl. the fractions of a second with the date_create_from_format](http://php.net/date_create_from_format) function:
$originalDate = "2016-07-23T07:00:00.000Z";
date_create_from_format('Y-m-d\TH:i:s.uO', $originalDate);
It does create a new DateTime which then can be formatted with the for PHP standard codes, e.g.
date_create_from_format('Y-m-d\TH:i:s.uO', $originalDate)
->format('Y-m-d H:i:s'); # 2016-07-23 07:00:00
As that W3C format carries the timezone already and it is UTC, and you wrote you want a different one, you need to specify it:
date_create_from_format('Y-m-d\TH:i:s.uO', $originalDate)
->setTimezone(new DateTimeZone('Asia/Tokyo'))
->format('Y-m-d H:i:s');
The reason why this is not visible (and controlable with the code given) in the previous answer is because date formats according to the default set timezone in PHP where as each DateTime has it's individual timezone.
An equivalent with correct parsing (incl. decimal fraction of a second) with the other answers then is:
$dateTime = date_create_from_format('Y-m-d\TH:i:s.uO', $originalDate);
date('Y-m-d H:i:s', $dateTime->getTimestamp());
Hope this explains it a bit better in case you need the complete date value and / or more control on the timezone.
For the format, see as well: In what format is this date string?
$oldDateTime= "2016-07-23T07:00:00.000Z"; // Your datetime as string, add as variable or whatever.
$newDateTime= date("Y-m-d H:i:s", strtotime($originalDate));
I have this date / time value (with timezone):
2019-10-22T17:00:00+02:00
Now I would like to check, which weekday this date is (for example: Monday)
and if this date has a difference of 1h between 16:00 o'clock and the date time.
How can I check the two factors as best practice ?
You may use DateTimeImmutable's constructor to parse the date string, DateTime#format to format it / retrieve the week day, and DateTime#diff to fetch the difference:
$date_string = '2019-10-22T17:00:00+02:00';
$date = new \DateTimeImmutable($date_string);
$date_at_16 = $date->setTime(16, 0);
echo $date->format('l'), PHP_EOL;
echo $date->diff($date_at_16)->h;
Demo: https://3v4l.org/R7e9n
Note that:
I've used DateTimeImmutable which is just like DateTime except it cannot be modified, so setTime doesn't also modify the initial date,
you should catch its constructor's potential thrown exception (if the format is invalid),
it should be better to use 'N' to retrieve the day of the week, as it's numerical and therefore more appropriate to store/compare (I've used 'l' for the purpose of this little demo, to get the full name),
if you need to know if it's 1 hour prior to or following 16 o'clock, you may check the DateInterval#invert flag (the date interval is what DateTime#diff returns).
I have a xml file, containing several dates, in this format: 2016-07-23T07:00:00.000Z. I'm using a php function to convert this in to a format for publishing on a website. This should actually result in something like Saturday, 24th of July (24th, not 23rd, because of the time offset. My function somehow ignores the T07:00:00.000Z part and thus returns Friday, 23rd of July. Can anybody help me out with the proper way to convert this date?
Thanks, Peter
The string in question
2016-07-23T07:00:00.000Z
is a W3C datetime format (W3C DTF) (Complete date plus hours, minutes, seconds and a decimal fraction of a second) which can be properly parsed incl. the fractions of a second with the date_create_from_format](http://php.net/date_create_from_format) function:
$originalDate = "2016-07-23T07:00:00.000Z";
date_create_from_format('Y-m-d\TH:i:s.uO', $originalDate);
It does create a new DateTime which then can be formatted with the for PHP standard codes, e.g.
date_create_from_format('Y-m-d\TH:i:s.uO', $originalDate)
->format('Y-m-d H:i:s'); # 2016-07-23 07:00:00
As that W3C format carries the timezone already and it is UTC, and you wrote you want a different one, you need to specify it:
date_create_from_format('Y-m-d\TH:i:s.uO', $originalDate)
->setTimezone(new DateTimeZone('Asia/Tokyo'))
->format('Y-m-d H:i:s');
The reason why this is not visible (and controlable with the code given) in the previous answer is because date formats according to the default set timezone in PHP where as each DateTime has it's individual timezone.
An equivalent with correct parsing (incl. decimal fraction of a second) with the other answers then is:
$dateTime = date_create_from_format('Y-m-d\TH:i:s.uO', $originalDate);
date('Y-m-d H:i:s', $dateTime->getTimestamp());
Hope this explains it a bit better in case you need the complete date value and / or more control on the timezone.
For the format, see as well: In what format is this date string?
$oldDateTime= "2016-07-23T07:00:00.000Z"; // Your datetime as string, add as variable or whatever.
$newDateTime= date("Y-m-d H:i:s", strtotime($originalDate));
After a long time I needed to use date function of PHP. I wrote something like:
echo date('now');
and I got the output below:
1220123
What does that mean ?
From the PHP manual :
n Numeric representation of a month, without leading zeros
o ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that
year is used instead. (added in PHP 5.1.0)
w Numeric representation of the day of the week
So, date("now") displays 12 (n), 2012 (o) and 3 (w).
You're probably looking for :
date("Y-m-d") for a date
date("Y-m-d H:i:s") for a datetime
"now" is not a valid parameter for for this expectation, infact it should be strtotime function here, not date.
Date considers your now as
n
Numeric representation of a month, without leading zeros
o
ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)
w
Numeric representation of the day of the week
you need to give a valid format to date function (not recognize the 'now' string as meaning of now )
$date = date("Y-m-d H:i:s");
or you can use the DateTime class
$date = new DateTime();
Seems you consider "now" as a word to get the current date and time, however it would compile on each character. Here is the explanation how it'll compile.
n = Month in number
o = It considers as a year in ISO-8601.
w = Week in number
So that's why it's returning you the date, year and number of week in a month.
Hope I can explain you bit easily.
"now" is not a valid parameter for date()
Correct syntax to print current date in
yyyy-mm-dd hours minutes seconds
format is as given below
echo date('Y-m-d h:i:s');
also see PHP manual for details of date() function
http://php.net/manual/en/function.date.php
I have a date that I am storing as a timestamp through the formatDate function in jQuery. I am then retriving this value to make an ics file, a calender file that adds the event time and details to the users calender. However the timestamp format isn't working in the ics file, the correct date isn't being added, so I need to convert it to a value that looks like 20091109T101015Z. It's current format as a timestamp looks like 1344466800000This is from this example which is what I am following to create my ics file.
My link to the php file is http:// domain. com/icsCreator.php?startDate=1344380400000&endDate=1345503600000&event=Space%20Weather%20Workshop&location=London
Current my ics file looks like
<?php
$dtStart=$_GET['startDate'];
$dtEnd=$_GET['endDate'];
$eventName=$_GET['event'];
$location=$_GET['location'];
...
echo "CREATED:20091109T101015Z\n";
echo "DESCRIPTION:$eventName\n";
echo "DTEND:$dtEnd\n";
echo "DTSTART:".$dtStart."\n";
echo "LAST-MODIFIED:20091109T101015Z\n";
echo "LOCATION:$location\n";
...
?>
See if this works:
date('Ymd\THis', $time)
Here $time could be startDate or endDate from your query string. If you don't want the time:
date('Ymd', $time)
NOTE (Thanks to Nicola) Here, $time must be a valid UNIX timestamp i.e. it must represent the number of seconds since the epoch. If it represents the number of milliseconds, you need to first divide it by 1000.
EDIT As pointed out by lars k, you need to add \Z to the end of both the strings.
EDIT As pointed out by Nicola, you don't really need it.
The \Z is telling the system the timezone. Z being Zulu or Universal time.
If you leave that out - then you are presuming that the timezone settings on the end users calendar application, match those of your system generating the timestamps.
In the USA alone there are multiple timezones - so you can't make that assumption just based on your users being in the same country as you.
In order for dates to go into the calendar correctly, you need to specify the timezone offset from UTC as plus or minus Hours and Minutes
NOTE:
date('Ymd\THisP') ; // P is an offset against GMT and should work for all calendar purposes.
That would out put somthing like this for a 1hr shift from GMT
20150601T10:38+01:00
When working with Dates in PHP it's best to use the DateTime object, then you can easily work with and change the timezones.
// Start with your local timezone e.g
$timezone = new \DateTimeZone('Europe/Amsterdam') ;
// Don't be tempted to use a timezone abbreviation like EST
// That could mean Eastern Standard Time for USA or Australia.
// Use a full timezone: http://php.net/manual/en/timezones.php
$eventdate = new DateTime ( '1st September 2015 10:30', $timezone);
// Convert the time to Universal Time
$eventdate->setTimezone( new DateTimeZone('UTC') ) ; // Universal / Zulu time
// Return Event Date/Time in calendar ICS friendly format
// comfortable in the knowledge that it is really in UTC time
return $eventdate->format('Ymd\THis\Z') ;