what is the second argument in date function meant for? - php

Can anyone please explain me the second argument of date function ?
string date ( string $format [, int $timestamp = time() ] )
What is it do,I mean what is it meant for ? I never used it except today when I had to do the following :
echo date('Y-m-d',strtotime('+1 day'));

Returns a string formatted according to the given format string using
the given integer timestamp or the current time if no timestamp is
given. In other words, timestamp is optional and defaults to the
value of time().
So if you leave it blank, you will echo the current date in the chosen format.
If you do as you do in your example and specify a timestamp it will format the specified timestamp. Your strtotime function converts +1day to an integer or timestamp format.

By default date() assumes you are referring to "now". If you want to use date with any other datetime other than "no" then you need to specify it using a timestamp.
var_dump(date("Y-m-d") === date("Y-m-d", time())); // bool(true)

This mean that you can represent unix time as string in any format. Unix time you can get from database or with strtotime.

The second parameter defaults to the current date/time.
So, if you want to print the current date, don't pass the second parameter:
echo date('Y-m-d');
If you want to print something other than the current date/time, like the date of one week from today:
echo date('Y-m-d', strtotime('+7 days'));

Related

strtotime() in php returning always 01-01-1970

I am using a variable to get the date from the database,then i am passing that variable to strtotime function to get the desired format,but it always returning wrong date.perhaps there is a problem in passing a variable in strtotime function.please suggest me guys,how should i get the correct date in correct format.
Here is what i am trying to do
$date = $fetch_user['date'];
$newDate = date("d-m-Y", strtotime($date));
$day = date('l', strtotime($newDate));
echo $newDate;
echo "-----";
echo $day;
exit;
January 1, 1970 is the so called Unix epoch. It's the date where they started counting the Unix time. If you get this date as a return value, it usually means that the conversion of your date to the Unix timestamp returned a (near-) zero result. So the date conversion doesn't succeed. Most likely because it receives a wrong input.
In other words, your strtotime($date) returns 0, meaning that $date is passed in an unsupported format for the strtotime function.
So you'll have to check for yourself $date, before calling strtotime at all.
01-01-1970 means you probably get 0 as a result of strtotime(). You are probably using a format, that this function cannot understand. The PHP documentation states:
The function expects to be given a string containing an English date
format and will try to parse that format into a Unix timestamp (the
number of seconds since January 1 1970 00:00:00 UTC), relative to the
timestamp given in now, or the current time if now is not supplied.
So it is not really flexible. You might want to try DateTime::createFromFormat instead. Take a look at it's documentation.
Basically you have to specify the format of the date string, that you give as an input as well. That way you can use whatever date format you want.
Example from php.net:
<?php
$date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');

Convert specific string to time in PHP

I need to convert a string into date format, but it's returning a weird error. The string is this:
21 nov 2012
I used:
$time = strtotime('d M Y', $string);
PHP returned the error:
Notice: A non well formed numeric value encountered in index.php on line 11
What am I missing here?
You're calling the function completely wrong. Just pass it
$time = strtotime('21 nov 2012')
The 2nd argument is for passing in a timestamp that the new time is relative to. It defaults to time().
Edit: That will return a unix timestamp. If you want to then format it, pass your new timestamp to the date function.
To convert a date string to a different format:
<?php echo date('d M Y', strtotime($string));?>
strtotime parses a string returns the UNIX timestamp represented. date converts a UNIX timestamp (or the current system time, if no timestamp is provided) into the specified format. So, to reformat a date string you need to pass it through strtotime and then pass the returned UNIX timestamp as the second argument for the date function. The first argument to date is a template for the format you want.
Click here for more details about date format options.
You are using the wrong function, strtotime only return the amount of seconds since epoch, it does not format the date.
Try doing:
$time = date('d M Y', strtotime($string));
For more complex string, use:
$datetime = DateTime::createFromFormat("d M Y H:i:s", $your_string_here);
$timestamp = $datetime->getTimestamp();

PHP date() function ignores the timestamp parameter

The output of the following program can be seen here: http://codepad.org/egNGJBUL
<?php
/* Checking if time() is really timezone independent */
date_default_timezone_set('UTC');
echo time();
echo "\n";
date_default_timezone_set('Australia/Queensland');
echo time();
echo "\n";
/* Using date() function passing timestamp parameter */
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s',time());
echo "\n";
date_default_timezone_set('Australia/Queensland');
echo date('Y-m-d H:i:s',time());
echo "\n";
/* Using date() function without passing timestamp parameter */
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s');
echo "\n";
date_default_timezone_set('Australia/Queensland');
echo date('Y-m-d H:i:s');
echo "\n";
From line 1-2 of the output, we can see time() returns a value which is really timezone independent.
In line 3-4, it's strange that date() function ignores the timestamp parameter and still display the date time according to the timezone set.
Why is it like this?
Not really sure what you are expecting to see, but yes, looks very normal to me.
A timestamp is a integer counted from a certain point in time (usually the UNIX EPOCH). While the display of this value is timezone independent, it is no more or less so that say, the value of a properly formatted date, notated with a timezone, is timezone independent...
example, all of the following statements are both true (logically)
1297799809 == 1297799809
2011-02-15 19:56:49 (UTC) == 2011-02-16 05:56:49 (Austria/Queensland)
All time is 'timezone independant'. Timezones only affect the way we display a particular moment in time.
date() functions second parameter, if not specified, is time() value.
date() Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().
from date()'s manual
So actually nothing is being ingnored.
The date function returns the date of a timestamp calculated for the current timezone, as others have said, if no timestamp is passed to it, then the current time is used for the timestamp, so passing time() is the same as not passing anything at all.
However, doing something like $time = time();sleep 5;echo date($format,$time); will get you a date 5 seconds in the past.
It's meant to display the date formatted for current timezone so you can have a universal method of keeping time that's constant across computers/servers and be easily parsable, and yet be able to display the date in any timezone desired.
The UTC timezone is actually the time that the timestamp is calculated to, more precisely, the number of seconds since 00:00 Jan 1, 1970 UTC, then it adds or subtracts 3600 (60*60) seconds from/to the timestamp per hour offset from UTC time to get the time in the currently set timezone.

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

How can I work out if a date is on or before today?

My web application consists of library type system where books have due dates.
I have the current date displayed on my page, simply by using this:
date_default_timezone_set('Europe/London');
$date = date;
print $date("d/m/Y");
I have set 'date' as a variable because I'm not sure if it makes a difference when I use it in the IF statement you're about see, on my library books page.
On this page, I am simply outputting the due dates of the books, many have dates which have not yet reached todays date, and others which have dates greater than todays date.
Basically, all I want is the due date to appear bold (or strong), if it has passed todays date (the system displayed date). This is what I have and thought would work:
<?
if ($duedate < $date) {
echo '<td><strong>';
} else {
echo '<td>';
} ?>
<?php echo $date('d/m/Y', $timestamp);?></strong></td>
I have declared $timestamp as a var which converts the date of default MySQL format to a UK version. Can anyone help me out? I thought this would've been very straight forward!
try:
if (strtotime($duedate) < time()) {
// oooh, your book is late!
}
Instead of working with the formatted dates, work with their timestamps. Either convert them back with strtotime() or use time() instead of date. Timestamps can be compared like regular numbers, because that's what they just are.
Okay :) Let's start here:
$date = date; // Wrong!
print $date("d/m/Y");
The above only works because PHP thinks date is a constant. But since you didnt set this constant PHP will convert it to the string 'date'. So $date contains 'date'. Then, when calling $date() as a function, PHP evaluates $date's content, which is 'date' and uses that as the function name, e.g. date(). What you really wanted to do was just $date = date('d/m/y').
Here is how date works:
string date ( string $format [, int $timestamp ] )
First argument is the desired output format, the second argument is an optional timestamp for which the output will be generated. If omitted it will be now. The function returns the output as string.
I assume your $duedates are already formatted strings, e.g. 2010-04-06. So when you do $duedate < $date, you are really doing a string comparison, because both variables hold formatted strings, but not timestamps.
Timestamps on the other hand are just numbers. A timestamp is the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). You can get the timestamp for the current date and time with the function time() and you can convert strings that represent dates with strtotime(). So when you want to compare your dates, do
if ( strtotime($duedate) < time() ) { // ... do something
And that's really all there is to it.

Categories