Show text after a date has passed - php

I am trying to get a simple line of text to appear if todays date is after another date.
I can either get it to appear on all pages or none, but I am unable to get it to display based on whether the challenge start date is before or after todays date. I believe it could be a date format issue, but everything I have tried has fallen short.
Here is my code:
Get todays date
$date_now = new dateTime();
Challenge start date
$challengeStartDate = date('dS F Y', strtotime($this->item->start_date));
echo '<!--' . strtotime('1970/1/1 00:00:00 +' . $validity) . '-->';
New text line
if ($challengeStartDate > $date_now) echo "New Text";

date() returns a string. With $challengeStartDate > $date_now it's like comparing if one string is bigger than the other (not sure if your dateTime handles that).
Your approach is otherwise fine. Just use timestamps to compare. time() gets you the time as a Unix timestamp:
$now = time();
if ($now > strtotime($this->item->start_date)) {
// do your thing
}
Something like this is more what you need. Try it out.

I had the very same problem some time ago.
All you need to do is store your local time in a database so it would be saved statically.
Because in your example, both $challengeStartDate and $date_now will change and update simultaneously and you wiill always get the current pc time!
Try storing it in a table or idk maybe sessions would help too.

Related

Unable to understand time() and date() functions

I am trying to get current time and date in order to echo it out on my website. I have the follow snippet:
$date_of_msg = date("Y-m-d");
$time_of_msg = time();
When I echo $time_of_msg I get 00:00:00. I have tried to edit my code based on this solution here but which this approach, when I echo the variable, I get 838:59:59. I simply want the current time to be displayed in 24 hour format.
In addition to this, I currently have the date formatted to (Y-m-d), which is great because it works. I am trying to format it so that it displays day, number, year, i.e. today is 20th Feb, so I want the date to display Feb 20, 2016. I have tried the following based on documentation (see here)
$date_of_msg = date("F j, Y")
But again, the date displays nothing. Am I missing something?
If you need the current time in the 24h format just use
$time_of_msg = date("H:i");
The date part seems correct that way, you must be doing something wrong while displaying it.
time() (unless you override it in some weird fashion) gives you a timestamp, i.e. the amount of seconds which have passed since 1970-01-01 until now. date(), however, gives you a string representation of a date, which may or may not include the minutes and seconds - depending on how you choose to format it.
So, if you want to display the time and date to a user, you should probably go for something like
$date_of_msg = date("F j, Y H:i:s")
The documentation on date() gives you an excellent description of available options.
time() returns a UNIX timestamp while date() format a timestamp. Your call date("Y-m-d") means the same as date("Y-m-d", time()).
Even though the function is called date(), it can also format time. You just have to use the correct placeholders. E.g. date("H:i:s") would give you a 24h-time like 17:43:23.
This code
<?php
echo date("Y-m-d").PHP_EOL;
echo time().PHP_EOL;
echo date("F j, Y").PHP_EOL;
Returns this result, as expected
2016-02-20
1455927480
February 20, 2016
So what are you doing that you are not actually telling us

Calculating the date weeks using the date() function

I have a website which saves images into a database. I have successfully made a function that calculates the date that an image is added and this value is also saved into the database. I now want to calculate the date two weeks ahead from the addition date. This will show the date that the image file will cease to exist in the database.
I used the function:
$dateofaddedimage= date("d/m/Y");
This calculate thee current date of the addition of the image.
I am aware that there is the strtodate() function, but i don't think it will help.
Does anyone know how to add two weeks onto this function?
Thanks!
Add a number to time(), which is the current time stamp as seconds from the Unix Epoch.
$twoweeks = time() + (2*7*24*60*60);
$thatasdate = date("d/m/Y", $twoweeks) ;
Check out date_add and the PHP DateTime model.
From the php manual page comes this fine example:
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
If you use this on your problem, you'd have
<?php
$dateofaddedimage = new DateTime('now'); //creates DateTime Model of today (and now)
$dateofimagedestroy = new DateTime('now'); //creates DateTime Model of today as well
$dateofimagedestroy->add(new DateInterval('P14D')); // adds 14 Days to the second date
The problem with what you are doing is that date() returns a string formatted to the date - not a proper date.
I would suggest either inserting a datetime into the database such as:
insert into yourTable (timeColumn) values (now());
This will insert the actual date. From there you can use mysql functions to add and subtract from this date.
Or using a timestamp in your code such as:
$uploadedTime=time();
From there you can either use PHP functions to add or subtract dates, or (as it is a timestamp) you can also use mysql functions to calculate what you need inside queries themselves.

How to insert time with am/pm format into the database

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.

Trying to convert from seconds to date

Okay so I have an array of results from a table, we have a start and end time we are retrieving. the start/end time would look something like this:
1345497551
Now I'm trying to convert this to a real time, for instance 1345497551 might become 2012/05/09 17:23:12 or something. I've found a few things but none seem to work correctly. one solution I tried, according to what someone was saying on another question on here, was
$createdate = date('H:i:s',$numberofsecs);
where $numberofsecs was the time pulled in from the array. but this only ever outputs 17:00:00 repeatedly for every time we had available for testing.
How can I go about making this work correctly?
Assuming that that's a standard unix timestamp string (seconds since midnight 1/1/1970), then you should be able to use date as you mentioned, but just modify the format string:
echo date('Y/m/d H:i:s', $numberofsecs);
The example you mention where you were always getting 17:00:00 could have been because your test cases were all only datestamps, encoded as timestamps, and having an offset from GMT . . .
I have tried below code:
$ts = 1345497551;
$date = new DateTime("#$ts");
echo $date->format('U = Y-m-d H:i:s');
output : 1345497551 = 2012-08-20 21:19:11

Why my comparison of two dates in PHP is not working?

I have removed the desired output and some styling as they dont affect the question. I cant seem to compare the two dates properly, idea is that if currentDate is greater than deadlineDate there will be no output for that route. What i am trying to do is prevent the system from listing routes which are already closed. I dont understand why its so difficult or then i am missing something very basic here.
<?php
$driveDays = mysql_query("SELECT date,routeid from StopDates where routeid='".$row['id']."' ORDER BY date ASC");
while($stopDates = mysql_fetch_array($driveDays)){
$orderDaysBefore = $row['lastOrderDate']; // How many days before the order must be placed.
// Change the date taken from the query to new format
$originalDate=($stopDates['date']);
$newDate = date("d.m", strtotime($originalDate));
// Count the deadline date for the route.
$deadlineDate = strtotime ("-".$orderDaysBefore." days +12 hours", strtotime ($originalDate)) ;
$deadlineDate = Date('d.m.y G:i', $deadlineDate);
//Get current date which is then compared to the deadline date. Idea is that if currentDate is larger than deadlinedate there will be no input.
$currentDate=Date("d.m.y G:i");
//The line below doesnt seem to be working, i have tried mktime and time too but for some reason it just cant compare.
if (strtotime($currentDate) > strtotime($deadlineDate)){
// Output nothing
}
else { ?>
<p>Output stuff here</p>
<?php
}
}
?>
Problem is that for some rows it hides the route and for some it doesnt. I have tried to do this with mktime and time but i cant seem to figure out what the problem is. Most of the guides i see tell to convert dates to unix timestamp format and if i understand correctly thats exactly what i am trying to do here. Im pretty sure my mistake is a simple one.
Strange thing is that for some dates it seems to work like if deadlineDate is over a month old. deadlineDate forms correctly in the d.m.y G:i format.
Solved
I skipped formatting and compared strtotimes
I added:
$currentDate2=strtotime("now");
$deadlineDate2 = strtotime ("-".$orderDaysBefore." days +12 hours", strtotime ($originalDate)) ;
And then i compare $currentDate2 and $deadlineDate2
Skip the formatting and just compare the results from strtotime().

Categories