I'm trying to use PHP to convert some of my database's datetime entries so that they appear with the full month name, day, and year: ex. July 08 2011
The entries in the database all have the correct dates and times, but when I try converting them, they show up in the correct format but the day becomes the month (08 shows up as August), the day shows up as the year (11), and the month shows up as the year (July shows up as 2007). So July 08 2011 gets converted to August 11, 2007.
Code:
$date2 = date('F j Y', strtotime($date));
Anyone know what might be up?
var_dump($date):
string(14) "07-07-11 01:32"
More code:
while($get_row = mysql_fetch_array($get_rs)) {
$gb_str2 .= $tableOpen;
$name = $get_row["Name"];
$email = $get_row["Email"];
$comment = $get_row["Comment"];
$date = $get_row["Date"];
if(!empty($name)) {
// If name exists and email exists, link name to email
if(!empty($email)) {
$name="by $name";
}
// If name does exist and email exists, link email to email
} elseif (!empty($email)) {
$name = "by $email";
// Else make name blank
} else {
$name = "";
}
// Append to string we'll print later on
$date2 = date('F j Y', strtotime($date));
$gb_str2 .= "$comment<hr>< posted on $date2 $name>".$tableClose."<br>";
}
For some reason,
$date = date('F jS Y', strtotime($get_row['date']));
did the trick. I still don't really understand what was going wrong.
Related
Hello i'm making a php script to send an email on a client's birthday, basicly i'm looping through every client's birthdates and checking with today's date and if they match, an email is sent. Although the date function is giving a random number instead of today's date, the number is: 1505451600.
Maybe i'm doing something wrong in the code? Does anyone know a way to fix this?
$get_birthday = $DB_con->prepare("SELECT email, dt_nascimento FROM clientes");
if ($get_birthday->execute()) {
while ($array_birthday = $get_birthday->fetch(PDO::FETCH_ASSOC)) {
$birthdate = date('m d', strtotime($array_birthday['dt_nascimento']));
// echo "</br> data:".$array_birthday['dt_nascimento'];
// echo "</br>".$birthdate;
$now = date("m/d");
$now = strtotime($now);
// echo "</br>now: ".$now;
$email = $array_birthday['email'];
if ($now == $birthdate) {
include"PHPMailer/email_birthday.php";
}
}
}
There are 2 changes you need to make for your code to work:
(1) Remove this line:
$now = strtotime($now);
Reason: You don't want a timestamp. You want a formatted date.
(2) Change "m d" on this line:
$birthdate = date('m d', strtotime($array_birthday['dt_nascimento']));
to "m/d" like so:
$birthdate = date('m/d', strtotime($array_birthday['dt_nascimento']));
Reason: you need to format $birthdate and $now the same way to make the comparison work.
I remove the $now conversion to timestamp and change the $birthdate format to the same as $now.
This is the working code :
$get_birthday = $DB_con->prepare("SELECT email, dt_nascimento FROM clientes");
if ($get_birthday->execute()) {
while ($array_birthday = $get_birthday->fetch(PDO::FETCH_ASSOC)) {
$birthdate = date('m d', strtotime($array_birthday['dt_nascimento']));
// echo "</br> data:".$array_birthday['dt_nascimento'];
// echo "</br>".$birthdate;
$now = date("m d");
// echo "</br>now: ".$now;
$email = $array_birthday['email'];
if ($now == $birthdate) {
include"PHPMailer/email_birthday.php";
}
}
}
The reason it gives you a number is how computers measure time is the number of seconds since 1/1/1970 00:00 (UTC (Universal Time)).
1505451600 Is equivalent to: 09/15/2017 # 5:00am (UTC)
this happens because:
date("m/d") returns 9/15 (today month/day)
then strtotime tries to convert this string into unix timestamp, as soon as year is not in string, current year (2017) is assumed
as soon as time part is not there, midnight in your timezone is assumed (5am utc)
this is why final time is 1505451600
I have the following function which works well but would like to check the returned date and compare with the current date if before current date to show something if current or in future show as normal.
Function:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
Call:
echo '<li class="list-group-item">Support Expires: ' . dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60 . '</li>');
Output:
2nd March 2016
So as not today's date and/or before today's date would like to echo a message, else just show the date.
In PHP it is very simple to compare two different dates using < = > like you normally compare numbers. The only step prior to this is below:
//Tell PHP that the value in variable is a date value
$date_1 = date_create("2017-05-29"); //This value can be any valid date format
date_1_formatted = date_format($date_1, "Y-m-d"); //This formats the date_1
//Now you can simply put the second date, for example, today.
$date_2 = date_create("2017-04-29"); //This value can be any valid date format
date_2_formatted = date_format($date_2, "Y-m-d"); //This formats the date_1
//For current date, it is simpler
$date_today_formatted = date("Y-m-d");
//Now you can compare these two dates easily
if ($date_1 < $date_today_formatted) {
echo "Date 1 falls before today.";
}
else {
echo "Date 1 falls after today.";
}
Hope this helps!
I managed to work it out using the following 2 functions:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
function checkLicenceSupport($licence_date) {
$date_now = new dateTime();
$date_set = dateFormat($licence_date, 11*60*60);
if ($date_now > $date_set) {
return 'date expired';
} else {
return 'date valied';
}
}
I have the following function which works well, but would like to
check the returned date and compare with the current date.
If it is before the current date, show something.
If it is the current date, or in future, show as normal.
I needed to rewrite your question, because lack of grammar and punctuation made it confusing. No offense intended.
Your call code has the closing parenthesis for your function call is placed wrongly.
dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60)
It is more readable to use full days or hours (in seconds):
11*86400 //(11 Days);
11*3600 //(11 Hours);
The function and code, as you have it now, will always return a date in the future of the date you've submitted via the call. (I can't tell from your question whether this was intended or not).
Currently, there is no "comparison" in your function. But your question indicates you want to compare the submitted date to the current date and then do something in certain cases.
If you are going to use a Unix timestamp, then there's no need for multiple formatting, compare the two dates in Unix, then format the result.
function dateCompare($submittedDate){
//This is only needed if your submitted date is not a unix timestamp already
$submittedDate = strtotime($submittedDate);
$currentDate = time(); // Creates timestamp of current datetime
if($submittedDate < $currentDate) {
//show something i.e. return "Support Has Expired";
}else {
return date('jS F Y', $submittedDate);
}
}
echo '<li class="list-group-item">Support Expires: '.dateCompare($purchase_data['verify-purchase']['supported_until']).'</li>';
I'm trying to retrieve a date data from mysql DB. But it returns N/A even though its not null. But when I comment out the 2nd If(statement) it returns January 01, 1970 but the actual data is June 6, 1952. BusDateHired and DateOfBirth
are in the same table. The membership date is perfectly fine, it retrieve the actual data from database.
# GET MEMBERS INFO.
$meminfo_sql = sqlCLIENTINFO($clientid, $br_code);
$meminfo_query = mysql_query($meminfo_sql) or die("ERROR GETTING MEMBER'S DATA".mysql_error());
$meminfo_data = mysql_fetch_array($meminfo_query);
# SET variables for members data.
$fullname = $meminfo_data['LName'].", ".$meminfo_data['FName']." ".$meminfo_data['MName'];
$temp_dateHired= explode("-", $meminfo_data['BusDateHired']);
$temp_dateopened = explode("-", $meminfo_data['DateOpened']);
$temp_birthDate= explode("-", $meminfo_data['DateOfBirth']);
# Date of Birth
$meminfo_birthDate= "";
if($meminfo_data['DateOfBirth'] != "No Data" || $meminfo_data['DateOfBirth'] != null || !is_null($meminfo_data['DateOfBirth'])){
$meminfo_birthDate = date("F d, Y", mktime(0,0,0,$temp_birthDate[1],$temp_birthDate[2],$temp_birthDate[0])); # date format January 01, 2013
}
#end of Date of Birth
# Date of hired..
$meminfo_dateHired= "";
if($meminfo_data['BusDateHired'] != "No Data"){
$meminfo_dateHired = date("F d, Y", mktime(0,0,0,$temp_dateHired[1],$temp_dateHired[2],$temp_dateHired[0])); # date-format January 01, 2013
}
if (is_null($meminfo_data['BusDateHired'])) {
$meminfo_dateHired = 'N/A';
}
# end of Date of hired
$meminfo_birthDate= "";
if($meminfo_data['DateOfBirth'] != "No Data" || $meminfo_data['DateOfBirth'] != null || !is_null($meminfo_data['DateOfBirth'])){
$meminfo_birthDate = date("F d, Y", mktime(0,0,0,$temp_birthDate[1],$temp_birthDate[2],$temp_birthDate[0])); # date format January 01, 2013
}
I have tried your code online with demo date its working fine.
echo date("F d, Y",mktime(0,0,0,02,03,2015));
Output:
February 03, 2015
Online DemoClick Here
A quick search didn't return any results that seemed to fit what I was looking for so I come here asking for your help.
I am working on formatting a birthday. The problem is, the use has the ability to enter only some (or none) of the data. It is stored separately as day, month, and year.
Basically, based on the data present will determine how the date will be formatted and displayed back to the user.
My approach is:
#prepare birthday
$bday = new DateTime();
$bday->setTimezone(new DateTimeZone('America/New_York'));
$bday->setDate($row->birth_year,$row->birth_month,$row->birth_day);
if($row->birth_month && $row->birth_year && $row->birth_day){
//Full birthday entered
$display_bday = $bday->format('F j, Y');
} elseif($row->birth_month && !$row->birth_year && !$row->birth_day){
//Only a month
$display_bday = $bday->format('F');
} elseif($row->birth_month && $row->birth_year && !$row->birth_day){
//Only Month and year
$display_bday = $bday->format('F, Y');
}
I was wondering if there is a better way to accomplish this task. I guess I figure there has to be a better way. Thanks in advance. If I need to clarify anything please just ask!
edit: removed unnecessary code
Your code could output invalid date since you are not filtering input when setting up a DateTime object. When the $row->birth_day equals 0, the DateTime object will move back to previous month (last date).
So, I suggest to consider that:
$display_bday = null;
if ($row->birth_month) {
if ($row->birth_year) {
if ($row->birth_day) {
// day, month, and year
$display_bday = date('F j, Y', strtotime("$row->birth_year-$row->birth_month-$row->birth_day"));
} else {
// month and year
$display_bday = date('F, Y', strtotime("$row->birth_year-$row->birth_month-01"));
}
} else {
if ($row->birth_day) {
// day and month
$display_bday = date('F j', strtotime("2016-$row->birth_month-$row->birth_day"));
} else {
// month only
$display_bday = date('F', strtotime("2016-$row->birth_month-01"));
}
}
}
I'm having an issue with time comparisons with PHP - I think I must be doing something stupid but I've been trying different things for hours now and I'm just hitting a brick wall.
I'm pulling data from EVE's API and then doing a check for whither there is still subscription there and whither there is a skill in training - with both of these there is a particular time frame (1 week for subscription and 12 hours for skills) that I'd like to flag up a warning - however I can't seem to get it working at all. The output of all the dates and times seems to be the right format I just can't get the comparison to work.
I'm wondering if anyone can point what's most likely my stupid mistake and give me a push in the right direction.
thanks for taking a look,
<?php
// ---- For Skill Queue
$apiSection = "char/SkillQueue";
$urlChar = "https://api.eveonline.com/$apiSection.xml.aspx?keyID=$keyID&vCode=$vCode&characterID=$charID";
$data = file_get_contents($urlChar);
$xml = new SimpleXMLElement($data);
foreach ($xml->result->rowset->row as $row){
$charQueueEndTemp = $row{'endTime'};
}
$charQueueEnd = date("d-m-Y H:m", strtotime($charQueueEndTemp));
//echo "Skill Test" . $charQueueEnd;
// --- Account API
$apiSection = "account/AccountStatus";
$urlAccount = "https://api.eveonline.com/$apiSection.xml.aspx?keyID=$keyID&vCode=$vCode";
$data = file_get_contents($urlAccount);
$xml = new SimpleXMLElement($data);
$accSubsTemp = $xml->result->{'paidUntil'}->{0};
$accSubs = date("d-m-Y H:m", strtotime($accSubsTemp));
date_default_timezone_set('Europe/Paris');
$currentDate = date("d-m-Y H:m");
$lessWeek = date("d-m-Y H:m", strtotime("-1 week"));
$plusWeek = date("d-m-Y H:m", strtotime("+1 week"));
$plus12Hour = date("d-m-Y H:m", strtotime("+12 hour"));
//Date Tests
//echo "</br> Curent Date: ".$currentDate;
//echo "</br> Plus Week: ".$plusWeek;
//echo "</br>Acc Subs: ".$accSubs;
//echo "</br>Acc +12: ".$plus12Hour;
// -- Account Subscribed Check
if($currentDate > $accSubs){
echo "Account is not Subscribed";
}
elseif($plusWeek > $accSubs){
echo "Account has less than 1 week Subscription";
}
else{
echo "Account is Subscribed";
}
// -- Skill Training Check
if($charQueueEnd = null){
echo "Skill Queue Ended";
}
elseif($plus12Hour > $charQueueEnd){
echo "Skill Queue ending in less than 12 Hours";
}
else{
echo "Skill Queue Active";
}
?>
Start using DateTime class for date/time manipulation/compare :
If you change your code to this :
$currentDate = new DateTime();
$lessWeek = new DateTime("-1 week");
$plusWeek = new DateTime("+1 week");
$plus12Hour = new DateTime("+12 hour");
... then your IF statements will start to work.
You are doing the date comparisons completely WRONG. You're comparing date STRINGS, e.g. using some dates formatted the same way you're doing:
$plusWeek = '26-08-2013 8:30'; Aug 26th, 2013
$accSubs = '9-08-2013 10:45'; Aug 9th, 2013
Since these are strings, string comparison rules apply. That means the strings are compared character by character, and (string)26 is actually LESS than string(9), because 2 is smaller than 9.
You need to keep things as the raw timestamps, e.g. the strtotime() output:
$plusWeek = strtotime('2013-08-26 08:30'); // 1377527400
$accSubs = strtotime('2013-08-09 10:45').; // 1376066700
Comparing these integer values will work as you want.
The main problem is also that you're not formatted your data strings in "most significant data" order. If they were formatted with the year first, e.g.
yyyy-mm-dd hh:mm:ss
then a string comparison WOULD work as a side effect.
If you want to compare dates you have to compare arguments returned by strtotime() function, for example:
elseif(strtotime($plus12Hour) > strtotime($charQueueEnd)){