DateTime::createFromFormat - php

I need to enter dates and time(input as strings) into my database but there's no change (remains as 0000-00-00 for the date and 00:00:00 for the time). I know I'm supposed to use DateTime::createFromFormat() but I'm not sure how to go about it. Please be patient and explain to me how I'm supposed to go about it and what is happening in each step and if I want to return the date from the database on later on, how will I go about it? I'm using $date and $starttime , $endtime.

While inserting, use STR_TO_DATE to convert your String date to Date or DATETIME based on the format as :
INSERT INTO TABLE1(date, startTime, endtime)
VALUES (STR_TO_DATE('$date','%d/%m/%Y'),
STR_TO_DATE('$starttime','%d/%m/%Y a%h:%i:%s'),
STR_TO_DATE('$endtime','%d/%m/%Y a%h:%i:%s'));
Similarly use DATE_FORMAT during retrieval to convert into string of desired format as:
SELECT DATE_FORMAT(date, '%d/%m/%Y') AS formatter_date,
DATE_FORMAT(starttime,'%d/%m/%Y a%h:%i:%s') AS formatted_startTime
DATE_FORMAT(endtime,'%d/%m/%Y a%h:%i:%s') AS formatted_endTime
FROM TABLE1;
Let me know, if you need further explanation.

Related

Insert date in specific format into MySQL db

I need to insert the current date in the following format into a TIMESTAMP column in a MySQL db: d-m-Y
As of now I am using SQL NOW(), which returns the date as Y-m-d. Because I am using AJAX to display the data I cannot format the returned result using $date_returned->format(d-m-Y). Therefore I need to insert the date in the format that I will display on my AJAX call.
I tried to insert the date using the following functions:
1) date('d-m-Y');
2) (new \DateTime())->format('Y-m-d');
I understand these two functions do pretty much the same thing but I was not sure what else I should try.
MySQL threw the following error for both dates:
Error : (1292) Incorrect datetime value: '-2014' for column 'msg_date' at row 1
I am guessing this should be an easy fix but I can't figure out what is wrong.
I tried both TIMESTAMP and DATETIME on MySQL's end but neither worked. (I need it to be TIMESTAMP though).
Any suggestion is welcome!
$newdate= date('Y-m-d', strtotime('10-09-2015'));
or if you want current time just use
$now = date('Y-m-d');
If your msg_date column's structure is DATETIME or TIMESTAMP, the date format should be:
YYYY-MM-DD HH:MM:SS
which can be formatted through PHP like this:
$date = date("Y-m-d H:i:s");
Or if you already have a date, and you want it to convert to that format, we can use strtotime():
$date = date("Y-m-d H:i:s", strtotime($date));
For more date format, check this link.
The MySQL error message indicated that you had the date format the wrong way around.
Year must go first, then month, then day, as in:
date('Y-m-d') // right
In your first example, you have
date('d-m-Y') // wrong
In one of your examples above, you have it right, but you say you got the same response, so I assume that was not what you actually tried.
Another thing to note is that a MySQL TIMESTAMP column stores both a date and time. It's valid to give MySQL just a date (MySQL will just leave the time at zero), but if you have no need to store a time, you may as well make the column DATE instead of TIMESTAMP.
If you want to display your dates as d-m-Y then by all means do so, but they need to be sent to MySQL as Y-m-d.

Convert date string to insert in mysql date format

I have a bunch of txt files that contains a lot of data, including a date in format
dd-mm-YYYY
for example this date
15-03-2014
Researching around here i found a way to convert this date to insert in database in the correct date format YYY-mm-dd
the query is
STR_TO_DATE('$array[12]', '%Y-%m-%d')
But i'm having weird results like
2019-07-20
How can i correctly insert them to database any tips of what i'm doing wrong?
The second parameter should be in the format your date is stores, not the format you're looking for which is always YYYY-MM-DD. So:
STR_TO_DATE('$array[12]', '%Y-%m-%d')
should be:
STR_TO_DATE('$array[12]', '%d-%m-%Y')

PHP MySQL date functions

I am working with dates, in both PHP as well as MySQL. EVerytime I use to convert date in unix format. But this time I have taken field in DB as date. But issue is it is taking yyyy-mm-dd format. I want to store it in dd-mm-yyyy format. Is this possible if I set default setting of DB. or each time I have to explode the dd-mm-yyyy format in PHP and convert it in YYYY-MM-DD format. Its my first query.
Second query is I wish to fetch the records from today's date. I mean dates after today's date. Like today then tomorrow then so on.... Is it possible to use order by on date field.
Just use:
$date = date('d-m-Y', strtotime($dateFromDB));
That will convert from MySQL DateTime to the format you have specified.
It is possible to order by date fields, e.g.:
SELECT *
FROM table
WHERE date > [yourDate]
ORDER BY date [DESC | ASC]
Your second requirement contradicts with the first one.
If you store your date in dd-mm-yyyy format, you'll be unable to sort your dates.
So - yes, you have to "explode" the dd-mm-yyyy date in PHP or format it any other way. That's not a big deal though. Everyone does it.
If you have a field of type 'datetime' you can use the MySQL-Command: FROM_UNIXTIME(%d) for conversion. 'order by' should be no problem.
Store the date in default format that is yyyy-mm-dd
when you want to display in front end
use the following query to
select otherFields, date_format(dateField,'%d-%m-%Y') from tableName;
For ordering by date
SELECT * FROM tbl
ORDER BY date DESC

PHP / MySQL storing and searching dates

Like many people, I am totally confused by the many date functions in PHP and MySQL. What I need is a to be able to store a date in MySQL and be able to view it on the screen in a human readable format, search on it by month, year, or combination of both using a standard web form, or sort it on months or years.
Example search would be all the records for febuary for the past 5 years.
I have a javascript calendar that inputs the month in the form as 02-12-2011.
What is the best format to use for this. What should the field be in MySQL.
Thanks
Please make use of the DateTime object.
Store the dates in mysql as a DATE format.
When writing the data
$date = new DateTime($_POST['date']);
or
$date = DateTime::createFromFormat('d-m-Y', $_POST['date']);
$query = sprintf("INSERT INTO `data` SET `date` = '%s'", $date->format('Y-m-d'))
When reading the data out create a DateTime object.
$date = new DateTime($row['date']);
Then you can print it in whatever format you want, e.g. You javascript's format:
echo $date->format('d-m-Y');
See
http://www.php.net/manual/en/class.datetime.php
and for date formats:
http://www.php.net/manual/en/function.date.php
As far as searches go, you can use mysql Date functions on the fields.
For all records in February for the last 5 years.
SELECT * FROM `data` WHERE MONTH(`date`) = 2 AND YEAR(`date`) >= YEAR(NOW()) - 5
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
The column type in MySQL should be date.
it's a date, so store it as a DATE column. You can either use UNIX_TIMESTAMP() in your SQL query or strtotime in PHP, to convert this back to a value that can be passed in to the php date() function, to output whatever format date you'd like.

Convert Date Format

I have a moodle installation in which there is a column in mdl_user table called firstaccess whose type is bigint(10) and contains date in following format 1266839570.
I am writing a query for accessing users according to date filters. For e.g. i want to check which users firstaccess is greater than '2010-04-12'. How can i convert the date? These two date formats are different. I think firstaccess is unix timestamp. Should i change the '2010-04-12' into unix timestamp or there is a way to convert firstaccess i.e 1266839570 to yyyy-mm-dd format.
Please help me on this.
Thanks
You can create a unix timestamp in php with the mktime() function, then simply put it in your query.
MySQL has a date_format() function, that can format dates however you like, but I'm not sure if it works with bigints. You'd better go with the mktime.
date() and mktime() are functions to concert from unix timestamp and back.
You can convert your dates in either way
I believe you can write your query using a timestamp. Eg.
SELECT * FROM mytable WHERE firstaccess >= TIMESTAMP('2010-04-12')
http://dev.mysql.com/doc/refman/5.0/en/timestamp.html
I don't know what form the date in your form is, but you can easily convert it to a timestamp (if it already isn't one) using mktime. For example:
$mytimestamp=mktime(0,0,0, $month, $day, $year);
Then just add it to your query:
$myQuery= "SELECT whatever FROM sometable WHERE " . $mytimestamp . ">=firstaccess";
Like Paul Peelen, my answer is a MySQL query. I'm going the other way, though, and converting first access into a date.
Using the date information in your problem:
SELECT * FROM mytable WHERE DATE_FORMAT(FROM_UNIXTIME(firstaccess), '%Y-%m-%d') > '2010-04-12';

Categories