Localize output of strtotime string - php

I read through manuals concerning strtotime and strftime as well as related functions, but I cannot seem to make any progress in trying to solve my problem.
Basically, I'm interested in ways to print output of $deldate5 in local language (Dutch in this case).
$deldate5 = date("d.m.Y., l", strtotime("today + 5 day", time()));
I would most likely need to ditch strtotime string and replace it with something else in order to facilitate "today + 5 day" parameter.
Can anyone help? Thank you in advance.

Let's pick this apart:
$deldate5 = date("d.m.Y., l", strtotime("today + 5 day", time()));
This is doing two things:
strtotime: Create a UNIX timestamp (number of seconds since the epoch).
date: Format the output.
Your problem is related to the output (2.), not creating the timestamp (1.). So let's put this apart:
$timestamp = strtotime("today + 5 day", time());
$formatted = date("d.m.Y., l", $timestamp);
The only thing required now is to deal with the following line of code:
$formatted = date("d.m.Y., l", $timestamp);
The formatting parameters for the dateDocs function are:
d - Day of the month, 2 digits with leading zeros
m - Numeric representation of a month, with leading zeros
Y - A full numeric representation of a year, 4 digits
l - A full textual representation of the day of the week
As l (lower case L) requires a locale in your output, let's see which formatting parameter strftimeDocs has to offer that is similar:
%A - A full textual representation of the day.
So it's just a small step to change from date to strftime:
$formatted = strftime("%d.%m.%Y., %A", $timestamp);
Hope this helps.

Try setting the date default timezone to your local timezone:
http://www.php.net/manual/en/function.date-default-timezone-set.php

Related

Output of php function "strtotime()" is confused

I have no idea about output of this function.
" strtotime(date("j"),date("F"),date("t")) "
Output: 1475734243
That output is changing according to the time.
my code block is:
<?php
$day= date("j");
$month= date("F");
$year= date("Y");
//calendar Variables
$currentTimeStamp= strtotime($day-$month-$year);
echo $currentTimeStamp;
?>
date("j") gives Day of the month without leading zeros (1 to 31).
date("F") gives A full textual representation of a month, such as January or March.
date("Y") gives A full numeric representation of a year, 4 digits (eg: 2016).
I am not sure what part is confusing but if I got it right that you want to display the current date with that format then you should use this without having to use strtotime()
echo date("j F Y");
Sample working output:
https://repl.it/Dodz/0
The output is a unix time stamp.
echo $day.'-'.$month.'-'.$year;
echo date('j-F-Y', strtotime($currentTimeStamp));
This will give you the answer you are looking for.
See strtotime documentation.
It returns the number of seconds passed since the U-day (January 1 1970 00:00:00 UTC) to the date (in string representation) that is provided as an argument. It's also called "Unix timestamp" and "Unix epoch (time)"

Date('now') in PHP

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

How to get last "particular (Ex. March)" month in PHP?

I want to display the last March month. I am using the following code,
date("Y-m-d",strtotime("last March"));
Any suggestions or references would be very helpful.
$year = date('Y');
if (date('n') < 3) {
$year--;
}
$beginningOfLastMarch = mktime(0, 0, 0, 3, 1, $year);
See http://php.net/date
date('M')
or
date('n')
or
date('m')
or, if you have a date
$mydate = "2010-05-12 13:57:01";
you can get like this
$month = date("m",strtotime($mydate));
m Numeric representation of a month, with leading zeros 01 through 12
n Numeric representation of a month, without leading zeros 1 through 12
I found a better way to do this but left my old solution at the bottom, as it may still be relevant for some people in certain use cases.
I found a better solution to my problem which involves prepending a date to strtotime, and then using the relative selectors. Say I wanted to select the 4th of March last year. I just do:
strtotime('{THIS_YEAR}-03-04 last year');
Obviously, before processing this string, I would replace {THIS_YEAR} with date('Y'). This works, simply because I hard code the values I want. 03-04 as 4th of March. I can replace these numbers with any date I like.
Old Solution
I figured out a solution that worked for me and it doesn't really involve writing any complex algorithms or anything. It does involve slightly extending the syntax of strtotime though.
Even though PHP's strtotime isn't perfect (for all use cases), I found that if you join strtotime's together, then you can make it extremely powerful.
Say if I wanted to select the 4th of last month, I can't really do that... strtotime doesn't really accept ordinals. I.E 4th.
However, I can do first day of last month, which is pretty close. All I need is to change the day.
strtotime allows a time() to be passed as a second argument. This means you can chain strtotime's like so:
$time = time();
$time = strtotime('first day of last month', $time);
$time = strtotime('+3 days', $time);
echo date('Y-m-d H:i', $time);
// I know we don't really need the initial `$time = time()`. It is there for clarity
which will give us the right time: 4th of last month.
This is where a little syntactic sugar comes in...
We can write a function that accepts partial strtotime strings separated by a delimeter:
function my_strtotime($str, $time = null, $delim = '|'){
$time = ($time==null ? time() : $time);
foreach(explode($delim, $str) as $cmd){
$time = strtotime($cmd, $time);
}
return $time;
}
Which can be used like so:
$str = 'first day of last month | +3 days';
echo date('Y-m-d H:i', my_strtotime($str));
And there we have it. 4th of last month.
There is no need to strip whitespace from the explode call, because strtotime already handles extra whitespace.
This can handle complex intervals like last year | first day of March | +9 days | 14:00 which will always return 10th of March at 2pm last year.
The best thing about this is that strings like last year | first day of March | +9 days | 14:00 can be generated with the required values, E.G.
last year | first day of {MONTH} | +{DAYS-1} days | {TIME}
This might need extra work to improve it, but I just wanted to quickly get this out here, so it may help others reaching this question

Past textual date to days (since) PHP

Hey guys,
how does one calculate the days past since a date like the one Twitter outputs in its API
eg:
Mon Jul 12 00:27:26 +0000 2010
to XXX
Can we do it with strtotime
Thanks guys,
Dex
Compatibility note: works only for PHP >= 5.3.0
Providing that the date format does not change, you can reverse the process (i.e. reverse timestamp -> string (on Twitters servers) to timestamp) using the exact date format. Using the table on the manual page of DateTime::createFromFormat:
<?php
$str = 'Mon Jul 12 00:27:26 +0000 2010';
$oDateTime = DateTime::createFromFormat('D M d H:i:s T Y', $str);
$unix_timestamp = $oDateTime->getTimestamp();
echo $unix_timestamp;
?>
Beware: On my machine, date('d-m-Y H:i:s', $unix_timestamp) differs two hours, the machines timezone is GMT+2.
To calculate the difference between in days between two Unix timestamps, use math (a day has 86400 seconds):
echo ($unix_timestamp1 - $unix_timestamp2) / 86400;
If you've two such dates, you can use DateTime::diff as suggested in the comments by Zerocrates. You've create two DateTime instances using DateTime::createFromFormat and invoke the DateTime::diff with two arguments passed, previously created DateTime instances. The returned DateInterval instance has a d property which contains the difference in days.
The other way would be using the getTimestamp method, doing the maths from the previous example.
References:
http://php.net/manual/en/datetime.createfromformat.php
http://php.net/manual/en/datetime.gettimestamp.php
http://www.php.net/manual/en/datetime.diff.php
http://www.php.net/manual/en/class.dateinterval.php
You can do it like that (where $your_date is the string you mentioned):
$diff = (time() - strtotime($your_date)) / (24*60*60);
In your case, when I did echo $diff; the output was (at the time I posted the answer):
321.85475694444
See more details for strtotime(), time() and date().
Hope this helped you.
You might find sth here:
performing datetime related operations in PHP
or in php manual there is a lot..
http://php.net/manual/en/function.date.php

PHP Time() to Google Calendar Dates time format

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

Categories