Format dynamic datetime - php

I apologize if this has been asked, I've just filtered through about 40 questions on this site and other sites about formatting dynamic datetime and have only seen answers for date() etc. The issue is that I am trying to format registration dates and last login dates for a member based system that currently is formatted as such: 2012-09-29 10:21:40 to Sep 2012but as this is dynamic data I am not sure how to do this. This information is pulled from the database as such, just for the sake of clarification:
$sql = mysql_query("SELECT * FROM members WHERE id='$id'");
while($row = mysql_fetch_array($sql)){
$username = $row['username']; // Ignore
$sign_up = $row["sign_up"];
$last_login = $row["last_login"];
}

As date() doc says:
date('M Y', strtotime($row["sign_up"]));

If you want to do it in PHP you must reformat the datetime from mysql youself:
$sign_up = date('M Y', strtototime($row["sign_up"]));
$last_login = date('M Y', strtototime($row["last_login"]));

If I understood it correctly, you wish to convert the DATETIME format to be displayed in PHP as something like Sep 2012. You may wish to look at date and strtotime too in the PHP Manual.
$sql = mysql_query("SELECT * FROM members WHERE id='$id'");
while($row = mysql_fetch_array($sql)){
$username = $row['username']; // Ignore
$sign_up = $row["sign_up"];
$last_login = $row["last_login"];
$convert = strtotime($sign_up);
$convert = date('M Y',$convert);
echo $convert . '<br />'; // this should be in the format Sep 2012
}

Related

PostgreSQL timestamp after converting to date, return date value - 01/01/1970

After inserting data from pstgrsql database I need to convert timestamp to date.
I tried php date() function but I only got value - 01/01/1970. Here is example of my code:
$query = "SELECT * FROM \"user\" WHERE verified= 't'";
$result = pg_query($conn, $query);
while ($row = pg_fetch_row($result)) {
$date = date('d/m/Y', $row[11]);
echo "\n";
echo "$row[0] , $row[1] , $row[3], $date ";
}
$ReportRow = array('date' => $date, 'activereg' => $activerag);
$ReportRow1 = array('date' => $date);
$ReportRow2 = array('date' => $date);
$report = array($ReportRow, $ReportRow1, $ReportRow2);
*there will be more data stored in these arrays but its just work in progress for now. Thanks all for any kind responses :)
EDIT 1
DB has rows like
`3125, alex, alex#example.com, 01/01/1970`
You are using date() to try to convert a string into a date, when date only accepts a full timestamp.
date(format,timestamp);
Rather, you want to convert your string in your result into a time value. Try
$time = strtotime($row[11]);
and if you need to switch it about use
$newformat = date('Y-m-d',$time);
If you need a timestamp after that, you can
$timestamp = $time->getTimestamp(); // Unix timestamp

Select date mysql request

I have the request below in a php file. I'm trying to get a date in this format: MONTHS-currentMonth-currentYear
$sql = "SELECT DAY(ADDDATE(`dateDebutC`, `dureeC`)) AS MONTHS FROM normalW WHERE id = '$id'";
If you want to format the date after returning the values from your sql query, then you can use the PHP date_format() function. Assuming you store the months value in a variable, let's call it $date:
echo date_format($date,'Y-m-d'); // Or whatever format you want to display
To add the current month and current year to that string, you can use the date() function:
$current_month = date(m); // prints current month in numeric format (01-12)
$current_year = date(Y); // prints current year as a 4-digit representation
$new_date = $date . '-' . $current_month . '-' . $current_year;
See https://www.w3schools.com/php/func_date_date.asp for a list of all parameters. And as a friendly reminder, please ensure that you are using mysqli rather than mysql, which is deprecated.
To get current month and year you can use GETDATE function in sql
$sql = "SELECT MONTH(ADDDATE(`dateDebutC`, `dureeC`))AS MONTHS,MONTH(GETDATE()) as curmonth,YEAR(GETDATE()) as curyear FROM normalW where id = '$id'";
Whatever this comes through as in result, for example, however you bind it:
$date = '2014-04-15 10:10:11';
$buildDate = new DateTime(strtotime($date));
$dowMonthDayYear = $buildDate->format('l F j, Y');
echo dowMonthDayYear // turns as April 15th, 2014
You can lookup datetime in php manual for other formats theres tons

Formating an Oracle timestamp with PHP

I want to separate Date and time from retrieved timestamp in oracle with php but it's not working. I tried to separate date and working after that i have to separate time but i am getting empty timestamp.
$db = $row['CREATEDATE']; // CREATEDATE=03-SEP-15 12.55.17.000000 PM
echo 'db...'.(string)$db."<br/>";
$timestamp = strtotime((string)$db);
echo 'timestamp...'.$timestamp."<br/>";
echo date("m-d-Y", $timestamp);
Convert your received column data to a string, and convert it to a datetime. Then you can do all other formatting on it.
$db = $row['CREATEDATE']; //$db need to be converted to string type
$datetime = new DateTime((string)$db); //I expect (string)$db will considered as a string
$date = $datetime->format('Y M d'); //convert to date
$time = $datetime->format('H:i:s'); //convert to time
$select_stmt = "select to_char(ENDTIME,' hh24:mi:ss') AS CHENG,to_char(RESERVETIME,' hh24:mi:ss') AS CHENG2 FROM RESERVATION WHERE RESERVATIONSTATUS='RENTING' AND RESERVATIONFACILITY = '".$_SESSION['cno']."'";
$stid = oci_parse($con, $select_stmt);
oci_execute($stid);
while ($row = oci_fetch_assoc($stid))
{
$datt=$row["CHENG"];
$datt2=$row["CHENG2"];
}

Adding current date to DATE table mysql ERROR

I am having some problems getting my date into my SQL table. I do not use datetime, but date.
This is the code I use, and the problem is that my SQL server doesn't recognize $date_add as a date and just puts the default 0000-00-00 in the date section...
if (isset($_POST['postbutton'])){
$articlepost = nl2br($_POST['article'])."<br>";
date_default_timezone_set('Europe/Oslo');
$datepic = date(YYYY-MM-DD);
$pictureurls = $_SESSION['urlpost'];
$thumbnail = 123;
$title = $_POST['title'];
$date_add = $datepic;
$articlepostimg = $articlepost.$pictureurls;
$insertpost = $db->prepare("INSERT INTO posts (title,post,date_add,thumbnail) VALUES (:title,:post,:date_add,:thumbnail)");
$insertpost->execute(array(':title' => $title, ':post' => $articlepostimg, ':date_add' => $date_add, ':thumbnail' => $thumbnail));
unset($_SESSION['urlpost']);
}
Here is what I see in my database after I submit my form:
Try the following:
$datepic = date("Y-m-d");
Here are the docs for date()
As for the question added in your comments, after you retrieve your date you'll need to do something like the following, where $orig_date is assigned the date retrieved from the database. As for converting it to Norwegian, I think you'd have to look into setlocale(), which I think warrants a different question.
$formatted_date = date('j, M Y', strtotime($orig_date));
You need to use either double quote or quotes to make date() function work propely
$datepic = date('YYYY-MM-DD');
This is just to add to already given answers after seeing OP asked for a language conversion in Norwegian, and by no means is it meant to step on anyone's feet, but as a complimentary answer.
You can use the following month conversion code which are in French, but you can easily modify it in Norwegian.
Notice that "Mars" is spelled the same way.
(This taken from my own code library)
<?php
// enter date format 2011-01-31 (Y-m-d)
function date_in_french ($date){
$week_name = array("Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi");
$month_name=array("","Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août",
"Septembre","Octobre","Novembre","Décembre");
$split = preg_split('/-/', $date);
$year = $split[0];
$month = round($split[1]);
$day = round($split[2]);
$week_day = date("w", mktime(12, 0, 0, $month, $day, $year));
return $date_fr = $week_name[$week_day] .' '. $day .' '. $month_name[$month] .' '. $year;
}
$currentDate=date('Y-m-d');
echo "Current Date: ";
echo date('D')." ".date('d')." ".date('M')." ".date('Y');
echo "<br>";
echo "Date in French => ".date_in_french($currentDate);
?>

Failing to compare php date with mysql date

Got stuck in a complex or maybe stupid problem. I am getting a query from mysql, and then trying to compare a date column with a PHP data which i formatted to the same format i.e "Y-m-d" it always results in no match, although i see there is a match.. and it gets the right result set too.
<?php
date_default_timezone_set('America/Los_Angeles'); // set timezone to our timezone
$constantTime = time(); // get value of time in constant
$appDate = date("Y-m-d", $constantTime); //that defines php time variable -
$queryDate = "SELECT * FROM date WHERE date='$appDate'";
$resultDate = mysql_query($queryDate) or die("Sorry Website Under Maintainence");
$recordDate = mysql_fetch_array($resulDate);
if ($appDate == date("Y-m-d", strtotime($recordDate['date']))) {
echo "MATCH ";
$dateID = $recordDate['dateID'];
} else {
mysql_query("insert into date(date) values('$appDate')")or die("Database write error1");
$resultDate = mysql_query($queryDate) or die("Sorry Website Under Maintainence");
$recordDate = mysql_fetch_array($resultDate);
echo "NO MATCH ";
$dateID = $recordDate['dateID'];
}
This is always triggering the else, i tried === instead of ==, i tried strcmp
As i assume you're comparing datetime field, you have two possibilities:
Cast field to date:
$queryDate = "SELECT * FROM your_table WHERE date(your_date_field) = date('$appDate')";
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date
or
Modify your date format to be ISO compatible:
$appDate = date("Y-m-d H:i:s", $constantTime); //it defines date in format 2015-03-14 15:00:00
$queryDate = "SELECT * FROM your_table WHERE your_date_field='$appDate'";
See also this question

Categories