I'm trying to store a date from a PHP form into an MS SQL database and am really struggling. The date is in string format, and in 'DD/MM/YYYY' format so I've tried to use strtotime() to convert it, but I just get 1970-01-01 01:00:00 from that.
The code I've tried is the following:
$requested = $_REQUEST["TextboxRequiredBy"];
var_dump($requested);
echo "<br/>";
$daterequested = date("Y-m-d H:i:s", strtotime($requested));
echo $requested . " becomes " . $daterequested . "<br/>";
mssql_bind($stmt, "#Parameter", $daterequested, SQLFLT8, false);
What I get on screen is:
string(10) "31/07/2012"
31/07/2012 becomes 1970-01-01 01:00:00
Warning: mssql_bind(): Unable to set parameter in xxx.php on line 110
Warning: mssql_execute(): message: Procedure or function 'SPNAME' expects
parameter '#Parameter', which was not supplied. (severity 16) in xxx.php
I've searched around and I just can't seem to find a way to convert the string successfully. I've used the following on another page that runs a date comparison, but this brings back an error that date_format() expects parameter 1 to be DateTime, boolean given:
$datefrom = date_create($requested);
$daterequestedfrom = date_format($datefrom,'Y-m-d H:i:s');
Can anyone suggest how I can successfully convert the string into a date?
That date format is not a default format. You probably want to look at the date_create_from_format function. This will allow you to specify the format of the time string you are trying to input.
Link to PHP documentation
For some reason, PHP doesn't like the slashes in strtotime. Convert them to dots and the script should work.
$requested = str_replace('/', '.', $_REQUEST["TextboxRequiredBy"]);
Related
I am using Laravel and I have to get some dates and store it on MySQL database.
When I create the date like this:
$date_sol = Carbon::createFromFormat("Y-m-d H:i:s","2020-12-10 01:00:00");
The date is properly stored on the database. However, I have to get the date from an input.
I am trying to get the date and then format it like this:
$novaData = $request->input('solicitacao_data') . ' 15:16:17';
$sol->data = Carbon::parse($novaData)->format("Y-m-d H:i:s");
However, I get the error:
DateTime::__construct(): Failed to parse time string (28/03/2020
15:16:17) at position 0 (2): Unexpected character
The error is at the line $sol->data = Carbon::parse($novaData)->format("Y-m-d H:i:s");
How do I make the formating conversion properly? I am new using Laravel. I am not sure about it.
For date format 'd/m/Y' try this.
Carbon::createFromFormat('d/m/Y', '22/02/2020')->toDateTimeString();
Similarly for date format Y-m-d try this
Carbon::createFromFormat('Y-m-d', '2020-02-22')->toDateTimeString();
output will be in format (Y-m-d H:i:s)
"2020-02-22 21:05:13"
Let's say you receive something as input.
Well, ideally you should first sanitize it, to make sure you received a string that can be interpreted as a date. For that, I would suggest you to have a look there :
php date validation
So, you assign the input to a var and append a string representing some time to it:
$novaData = $request->input('solicitacao_data'). ' 15:16:17';
From here, the easiest is to convert the string into a timestamp. Which can be achieved this way:
$time = strtotime($novaData);
And now, you can use Carbon to format the date the way you want :
$sol->data = Carbon::createFromTimestamp($time)->format("Y-m-d H:i:s");
I want to change given date and time or date only into Unix time.
I tried like this:
mktime("Jan-12-2012 2:12pm");
But it’s not working:
Even in PHP documentation I looked at many examples and many of them don’t consist the matter that I want.
And when I try:
$user_birthday=$_POST["user_birthday"];
$db_user_birthday=empty($user_birthday)?"":mktime($user_birthday);
$_POST["user_birthday"] was given value from form that is jan-12-2012 2:12pm
it show error like this:
Notice: A non well formed numeric value encountered in C:\Program
Files (x86)\Ampps\www\admin\index.php on line 76
How do I fix it or display time into Unix?
Use this one:
date("M-d-Y h:i:s", strtotime($user_birthday));
You should be using strtotime instead of mktime:
Parse about any English textual datetime description into a Unix
timestamp.
So your code would be this:
$user_birthday = $_POST["user_birthday"];
$db_user_birthday = empty($user_birthday) ? "" : strtotime($user_birthday);
Then you can process that date like this to get it formatted as you want it to:
echo date("M-d-Y h:ia", $db_user_birthday);
So your full code would be this:
$user_birthday = $_POST["user_birthday"];
$db_user_birthday = empty($user_birthday) ? "" : strtotime($user_birthday);
echo date("M-d-Y h:ia", $db_user_birthday);
Note I also added spaces to your code in key points. The code will work without the spaces, but for readability & formatting, you should always opt to use cleaner code like this.
You should take a look at this answer: convert date to unixtime php
Essentially, you have mixed up mktime() with strtotime(). strtotime() allows you to parse an English textual string into a Unix timestamp. mktime() constructs a unix datetime based on integer arguments.
For example (again taken from the question above)
echo mktime(23, 24, 0, 11, 3, 2009);
1257290640
echo strtotime("2009-11-03 11:24:00PM");
1257290640
I am new to PHP and I am trying to learn more of php date and time but I seem to get stuck with this.
I have this date format:
ddMMyyHHmmss
And an example is 120813125055 but I am trying to manipulate the string such that it will give me the format of:
yyyy-MM-dd HH:mm:ss (in the example above, 2013-08-12 12:50:55)
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
But it always gives me a result of 1969-12-31 18:00:00.
I assume that I need to do some string manipulation in PHP for this but I was wondering if there is an easier and more efficient way to do it?
I think what you're looking for is in the second response answered here: how to re-format datetime string in php?
To summarize (and apply to your example), you could modify the code like this.
$datetime = "120813125055";
$d = DateTime::createFromFormat("dmyHis", $datetime);
echo $d->format("Y-m-d H:i:s");
Use date_create_from_format:
$ts = date_create_from_format('dmyHis', '120813125055');
$str = date('Y-m-d H:i:s', $ts);
strtotime() only works on EASILY recognizable formats. Your is a ugly mix of garbage, so no surprise that strtotime bails with a boolean FALSE for failure, which then gets typecast to an int 0 when you tried feed it back into date().
And of course, note that your time string is NOT y2k compliant. two digit years should never ever be used anymore, except for display purposes.
You're using your function call and the argument the wrong way around.
In your example, php will try to return you the date for which the time is 'strtotime('120813125055')', and this function returns false (interpreted as 0). So you get returned the date formatted in 'Y-m-d H:i:s' for the Unix epoch.
You will need to get the actual timestamp of your string, so use http://www.php.net/manual/en/datetime.createfromformat.php.
You are mistaken here..
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
You shouldn't use only numbers ( doesnt matter its an integer or a string ), than it will always give you the same thing.
You can use any other valid date and time ( E.G. 6 Jun 2013, 5 may 12...) . Because what strtotime() do is detect a valid date and convert it into timestamp.
How to get date format of given string, string contain a valid date
I am try to import data from csv file, and that csv files are exported for backup
but there are so many different type of date format and in some case when i try to convert string to date it throwing me an error
ex: 04/08/2010 10:22 am
some time this type of format throwing me error
Error 500: DateTime::__construct(): Failed to parse time string
You can use just strtotime
echo date('Y-m-d H:i:s', strtotime('04/08/2010 10:22 am')); // output: 2010-04-08 10:22:00
You can use the DateTime::createFromFormat() static method.
Also, you may want to do some reading:
DateTime::__construct() reference
Supported Date and Time Formats
Date/Time extension reference
Also, you need to use the search function (top right on the page). There are a lot of questions that deal with similar problems.
Try this...........
$today = date("d/m/Y g:i a");
<?php
$today = date("d/m/Y g:i a");
echo $today;
?>
You will get output like this.........20/02/2013 7:53 am
For sample one see this example link
I am going round in circles with this one! I'm doing the following:
Retrieving a date from an MSSQL datetime field via SQL/PHP
Sending the date to a new PHP page via the querystring
Trying to use that date in a new SQL query
I'm hitting problems here.
If I use echo:
echo $_REQUEST['rSessionDate'];
output: 15/10/2012
Which is fine, but when I use it in a SQL query I'm not getting the results I expect, so I thought the best thing to do would be to make sure it's being recognised as a date first.
If I use date_format():
echo date_format($_REQUEST['rSessionDate'],'Y-m-d');
output: Warning: date_format() expects parameter 1 to be DateTime, string given in ...
If I use strtotime():
echo strtotime($_REQUEST['rSessionDate']);
output: (nothing)
If I use date():
echo date('Y-m-d H:i',$_REQUEST['rSessionDate']);
output: Notice: A non well formed numeric value encountered in ...
If I use date() with strtotime():
echo date('Y-m-d H:i',strtotime($_REQUEST['rSessionDate']));
output: 1970-01-01 01:00
I'm sure I'm totally missing something simple.
EDIT: I've tried a few new functions I found:
$rSessionDate = new DateTime($_REQUEST['rSessionDate']);
echo $rSessionDate->format('Y-m-d H:i:s');
output: Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (15/10/2012) at position 0 (1): Unexpected character'
and:
$rSessionDate = date_create($_REQUEST['rSessionDate']);
echo date_format($rSessionDate, 'Y-m-d H:i:s');
output: Warning: date_format() expects parameter 1 to be DateTime, boolean given i
EDIT 2:
I have tried using CAST:
SELECT fCourseCode ,fCourseTitle FROM tCourses WHERE fCourseCode = '4B' AND (ISNULL(fValidStart, 0) <= CAST('2012-10-15 00:00:00' as DATETIME))
But this fails with error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value"
These might help to shed some light on what you're looking for.
http://www.ozzu.com/programming-forum/php-mssql-datetime-field-not-pulling-correctly-t106226.html
http://af-design.com/blog/2010/03/13/microsoft-sql-server-driver-for-php-returns-datetime-object/
strtotime() is returning an epoch timestamp in your example above.
or check CAST and CONVERT (refers to MSSQL2000 but may still help you)
http://msdn.microsoft.com/en-us/library/aa226054%28SQL.80%29.aspx
if the date was retrieved from an MSSQL table and you want to use strtotime() in PHP and also don't want to change the date format to yyyy-mm-dd then you can use
CONVERT(VARCHAR(30), DateFromMSSQL, 121) as DateFromMSSQL