Query in Microsoft SQL Server using Datetime Convert - php

I want to know how can I query data using datetime convert:
Example if in ORACLE using :
WHERE TO_CHAR(FQA_END_DATE,'YYYY-MM-DD') = '2014-03-25'
How about in SQL Server ?
WHERE ...
Please help to advice.
Thanks

In sql server you can do something like
WHERE CAST(Date_Column AS DATE) = '20140325' --<-- 'YYYYMMDD' ANSI Standard
or
WHERE CAST(Date_Column AS DATE) = CAST(GETDATE() AS DATE)

If FQA_END_DATE is a datetime datatype; you do not need to make a conversion to characters to compare it to a character string. You just need to provide the character string in an unambigious format, which for example would be the ISO format yyyyMMdd;
so if FQA_END_DATE is a datetime this would work:
WHERE FQA_END_DATE = '20140325'
If however,t hen FQA_END_DATE contains a time portion as well as date, and you're only interested in comparing on date part (and you do not have DATE data type), a good number of methods exists, but a trick is to run it past float;
WHERE CAST(FLOOR(CAST(FQA_END_DATE AS FLOAT)) AS DATETIME) = '20140325'
That converts/removes the time portion from your datetime variable.
The same can also be achieved by using DATEPART or DATEDIFF functions.
Ultimately - you can use the CONVERT to convert both sides of the WHERE into the same date format;
WHERE CONVERT(DATETIME, FQA_END_DATE, 112) = CONVERT(DATETIME, '20140325', 112)
Many many approaches exists to this issue, hopefully this will give some inspiration.
The best advice I can give you is if handling dates as string, to use the ISO format of yyyyMMdd (20140325) because SQL Server can automatically convert that.

Related

how to add one month in a raw date coming from oracle using PHP only?

Let's say I have this date, e.g.:
12-DEC-14 11.55.51.000000000 AM
and then I assigned it to variable, let's say:
$date = '12-DEC-14 11.55.51.000000000 AM';
Now the question is, how do I add 1 month or 2 months or so to that $date using only
php, without using any oracle sql date functions, just pure php,
because I will save the result to oracle db table in that same format.
The result should be like, e.g.:
$nextmonth = '12-JAN-15 11.55.51000000000 AM';
Then that's the time I can save that $nextmonth in the table column. So how ?
You can use DateTime classes in this case, load that date and define its format. Then after creating the datetime object, adjust it to your x number of months, then present it again with the original format.
$input = '12-DEC-14 11.55.51.000000000 AM';
$date = DateTime::createFromFormat('d-M-y h.i.s A', $input);
$next_month = clone $date;
$next_month->modify('+1 month');
echo strtoupper($next_month->format('d-M-y h.i.s A'));
This is probably only a very long comment rather than a real answer, but some of your comments let me think we have an instance of XY problem here:
it's a TIMESTAMP(6) , but the format is exactly like this inside that column 12-DEC-14 11.55.51.000000000 AM
how bout the succeeding 9 zeroes ?, won't that cause any errors in oracle if I just append it like e.g echo strtoupper($next_month->format('d-M-y h.i.s.000000000 A'));
A TIMESTAMP(6) store a date-time information (a "point in time"). It hasn't any "format" par se. TIMESTAMP are great data type, as they allow you to easily perform calculation on data and time with a great precision at DB level such as "adding one month".
But, without explicit request from your part, a default format is used to convert timestamps from and to strings.
Maybe your real issue is that Oracle try to implicitly convert your string to timestamp using its standard format. Usually, it is a far better idea to explicitly convert data type yourself. From the documentation:
Oracle recommends that you specify explicit conversions, rather than rely on implicit or automatic conversions, for these reasons:
[...]
implicit conversion depends on the context in which it occurs and may not work the same way in every case. For example, implicit conversion from a datetime value to a VARCHAR2 value may return an unexpected year depending on the value of the NLS_DATE_FORMAT parameter.
Please note that above statement is true for TIMESTAMP too, as the "standard" format is user-definable using NLS_TIMESTAMP_FORMAT.
The PHP documentation has a similar warning:
DATE columns are returned as strings formatted to the current date format. The default format can be changed with Oracle environment variables such as NLS_LANG or by a previously executed ALTER SESSION SET NLS_DATE_FORMAT command.
As a personal suggestion, I would say that you should never rely on implicit date/timestamp conversion, as any change of the relevant configuration settings at DB-level or for the current session will break your code.
So, depending the way you insert your value, using an explicit format might be as simple as wrapping the bind variable in a proper TO_TIMESTAMP(....) call:
// query the original data
$q = oci_parse ($connection ,
"INSERT INTO ....
VALUES (TO_TIMESTAMP(:date_as_str, 'YYYY-MM-DD HH:MI:SS.FF'), other_columns...)");
$q = oci_parse ($connection ,
"INSERT INTO ....
VALUES (TO_TIMESTAMP(:date_as_str, 'YYYY-MM-DD HH:MI:SS.FF'), other_columns...)");
Coming back to your initial question: "how to add one month in a raw date" " I will save the result to oracle db table in that same format data type" , this should be as simple as adding 1 month when inserting the value:
$q = oci_parse ($connection ,
"INSERT INTO ....
VALUES (TO_TIMESTAMP(:date_as_str, 'YYYY-MM-DD HH:MI:SS.FF')
+ INTERVAL '1' MONTH, other_columns...)");

MYSQL mixing up dates

I am trying to insert a date in my Database which I get from a php input.
The code I am using to insert the value looks like this
$length = strrpos($fristdatum, " ");
$newDate = explode(".", substr($fristdatum, $length));
$fristdatum = $newDate[2] . "-" . $newDate[1] . "-" . $newDate[0];
Lets say I enter 14.12.2012 as the date if I echo $fristdatum I get 2012-12-14 but as soon as I insert it in my MySQL DB it turn to 2014.12.20 any ideas?
The Column Type is date. The insert is somewhat like this
mysql_query("INSERT INTO sch_anschreiben (date)values('$fristdatum'))
there are more values but I guess that doesn't matter
Thanks in Advance!
Well thanks for the help guys i figured it out i used $fristdatum in a array for str_replace ,after i formated it, like this
$patern = array("[Date]")
$words=array($fristdatum)
$content = str_replace($patern, $words, $content);
and after that inserted it in the DB now I changed it so it would format after the str_replace and it seems to work just fine.
also would appreciate if someone could explain me why^^.
Instead of explode and hard coded conversion, prefere using DateTime::createFromFormat if you have PHP 5.3 or later.
$date = DateTime::createFromFormat('d. m. Y',$fristdatum);
echo $date->format('Y-m-d');//echoes 2012-12-14
Now that you correct your script to register your dates the right way, you should ensure your database is good.
You can use this request I think :
UPDATE yourtable SET yourdate=CONCAT(MONTH(yourdate),'-',DAY(yourdate),'-',YEAR(yourdate)) WHERE MONTH(yourdate) > 12
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
So if you want to store it like 14-12-2012 then use its datatype as varchar.
Convert it into Y-M-D format. You should directly put 2012-12-14 onto your database.

How do I store an UTC ISO8601 date in a MySQL database?

I have thousands of dates in the following format:
2011-10-02T23:25:42Z (aka ISO 8601 in UTC)
What MySQL data type should I use for storing such a ISO8601 date in a MySQL database? E.g. Datetime, timestamp or something else?
Which is best for comparison (eg. getting records between two dates/times) and ordering the results from queries? What about if the database is very large?
And what would be the best way to convert the above PHP string for MySQL storage? (I'm guessing date_default_timezone_set('UTC'); would be used?)
I think that keeping your date-time values in field of type DATETIME would be kind of natural way.
From my own experience with my current PHP application, only read / write operations concerning this information may be problematic.
One of possible solutions (assuming that you use DATETIME data type) for properly performing the whole process could be the following approach:
Reading DATETIME values for PHP use
Acquire DATETIME fields from your database converting them in the query to string representation in the form of '2011-10-02T23:25:42Z' by using DATE_FORMAT MySQL function with '%Y-%m-%dT%H:%i:%sZ' formatting string (docs on DATE_FORMAT)
Read fetched column value in this specific format and convert it in PHP from string to real date-time representation valid for PHP (such as DateTime class objects and DateTime::createFromFormat static method given 'Y-m-d\TH:i:s\Z' formatting string (T and Z are escaped to avoid treating them as formatting directives) (docs for the method).
Use converted values as real date-time values with all the logic applicable, like real date comparisons (not text-comparisons), etc.
Writing PHP date-time to MySQL database
Convert i.e. PHP DateTime class object to our ISO 8601 in UTC format string representation using DateTime class object's format method with the same as before 'Y-m-d\TH:i:s\Z' formatting string (documentation).
Perform INSERT / UPDATE operation on database information using such prepared string as a parameter for MySQL function STR_TO_DATE (with '%Y-%m-%dT%H:%i:%sZ' formatting string) which converts it to real database DATETIME value (docs on STR_TO_DATE).
Example code in PHP
Below please find a draft example of such approach using PDO objects:
$db = new PDO('mysql:host=localhost;dbname=my_db;charset=utf8', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// run the query aquring 1 example row with DATETIME data
// converted with MySQL DATE_FORMAT function to its string representation
// in the chosen format (in our case: ISO 8601 / UTC)
$stmt = $db->query("SELECT DATE_FORMAT(dt_column, '%Y-%m-%dT%H:%i:%sZ') AS formatted_dt_col"
." FROM your_table LIMIT 1");
if($stmt !== FALSE) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// convert the acquired string representation from DB
// (i.e. '2011-10-02T23:25:42Z' )
// to PHP DateTime object which has all the logic of date-time manipulation:
$dateTimeObject = DateTime::createFromFormat('Y-m-d\TH:i:s\Z', $row['formatted_dt_col']);
// the following should print i.e. 2011-10-02T23:25:42Z
echo $dateTimeObject->format('Y-m-d\TH:i:s\Z');
// now let's write PHP DateTime class object '$dateTimeObject'
// back to the database
$stmtInsertDT = $db->prepare("INSERT INTO your_table(dt_column) "
. " VALUES ( STR_TO_DATE(:par_formatted_dt_column, '%Y-%m-%dT%H:%i:%sZ') )");
$dtAsTextForInsert = $dateTimeObject->format('Y-m-d\TH:i:s\Z');
// convert '$dateTimeObject' to its ISO 8601 / UTC text represantation
// in order to be able to put in in the query using PDO text parameter
$stmtInsertDT->bindParam(':par_formatted_dt_column', $dtAsTextForInsert, PDO::PARAM_STR);
$stmtInsertDT->execute();
// So the real insert query being perform would be i.e.:
/*
INSERT INTO your_table(dt_column)
VALUES ( STR_TO_DATE('2011-10-02T23:25:42Z', '%Y-%m-%dT%H:%i:%sZ') )
*/
}
}
catch(\PDOException $pexc) {
// serve PDOException
}
catch(\Exception $exc) {
// in case of no-PDOException, serve general exception
}
This approach helped me a lot in operating date-time values between PHP and MySQL database.
I hope it might occur helpful for you also.
You can use DateTime data type for storing the date and time.
Use CAST function to cast such strings into mysql DateTime type.
Here is an example:
CAST("2011-10-02T23:25:42Z" AS DATETIME)
This will give you 2011-10-02 23:25:42.
Hope this will help you.
You can easily convert the date using strtotime function of php :
date_default_timezone_set('UTC');
$date = '2011-10-02T23:25:42Z';//(aka ISO 8601 in UTC)
$time = strtotime($date); //time is now equals to the timestamp
$converted = date('l, F jS Y \a\t g:ia', $time); //convert to date if you prefer, credit to Marc B for the parameters
Now you would simply insert your date in MySQL using timestamp or datetime depending on which one fit the most your needs. Here the most important things you should know about both types.
Timestamp
Range of '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC
Affected by the time-zone setting.
4 bytes storage
allow on update current_timestamp on columns for all versions.
Index is way faster
NULL is not a possible default value
Values are converted from the current time zone to UTC for storage, and converted back from UTC to the current time-zone for retrieval.
Datetime
Range of '1000-01-01 00:00:00' to '9999-12-31 23:59:59'
Constant (time-zone won't affect)
8 bytes storage
allow update on columns only as of version 5.6.5
Which is best for comparison (eg. getting records between two
dates/times) and ordering the results from queries? What about if the
database is very large?
According to the previous points I stated, then you should use timestamp for a very large database as the storage is smaller, and the index faster which will give you better performance for comparison. However, you MUST MAKE SURE your date will fit the limits of the timestamp I previously mentioned, else you have no choice and must use datetime.
Documentation for strtotime : http://php.net/manual/en/function.strtotime.php
And please, for the sake of SO's answerer who keep repeating every day to not use the mysql* DEPRECATED functions, please use PDO or mysqli* when you will do your inserts.
http://php.net/manual/en/book.pdo.php
http://php.net/manual/en/book.mysqli.php
You can not store date in raw UTC ISO8601 format (with 2011-10-02T23:25:42Z representation) and save all SQL DATETIME functionality.
But you should know, that MySQL ( regarding to http://dev.mysql.com/doc/refman/5.5/en/datetime.html ) always store time/date in UTC.
Also you can modify timezone for your connection
http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
So, if you execute in PHP
date_default_timezone_set('UTC');
and in MySQL
SET time_zone = +00:00
sure PHP and MySQL would use UTC.
After that you can convert all database strings to DateTime without caring about timezone mismatch.
To convert any PHP DateTime (without carrying about its internal timezone) to MySQL datetime string you should set DateTime object timezone to UTC.
$datetime->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
Using your datetime on my system which is PDT:
SELECT CONVERT_TZ(str_to_date('2011-10-02T23:25:42Z','%Y-%m-%dT%H:%i:%sZ'),'+00:00','SYSTEM') from dual;
2011-10-02 16:25:42
If your datetime has a fractional microsecond; include the .%f before the Z as follows:
SELECT CONVERT_TZ(str_to_date('2011-10-02T23:25:42.123456Z','%Y-%m-%dT%H:%i:%s.%fZ'),'+00:00','SYSTEM') from dual;
2011-10-02 16:25:42.123456
Here are the points why it is better to use datetime.
With datetime you will be able to do date manipulations on mysql side - such as subtracting day,month
You will be able to sort data.
If DB is huge - varchar takes more place on HDD

Converting string to MySQL timestamp format in php

I am writing a query in php using a string sent from a android java application.
The query is something like :
$insertSQL = sprintf("INSERT INTO app_DuckTag (taste) VALUES (%s) WHERE species=%s AND timestamp=%s",
GetSQLValueString($_POST['taste'], "text"),
GetSQLValueString($_POST['species'], "text"),
GetSQLValueString($_POST['timestamp'], "text"));
But I doubt timestamp is stored as a string inside MySQL.
How should I convert the string to time format as in MySQL?
The strtotime(string) php function converts it to unix time.
But the MySQL stores it differently, I guess. Thank you.
EDIT: This is how it shows up in MySQL phpmyadmin: 2011-08-16 17:10:45
EDIT: My query is wrong though. Cannon use a where clause with Insert into.
The query has to be UPDATE .... SET ... = ... WHERE ....
But the accepted answer is the correct way to use the time inside the WHERE clause.
This should be all:
date("Y-m-d H:i:s", strtotime($_POST['timestamp']));
if you want to check for timezones and such you should use strftime instead of date
If you can get the input 'string' (which you haven't provided the format that you're receiving it in) to a Unix timestamp value, you can easily convert it to a MySQL datetime format like this:
$mysqldatetime = date("Y-m-d H:i:s", $unixTimeStampValue);
This will produce a string similar to the following:
2011-08-18 16:31:32
Which is the format of the MySQL datetime format. If you are using a different time format, then the first argument to the date function will be different.
See the manual for the date function for more information and other ways you can format the value that it returns.
Edit
You are receiving a string formatted in MySQL datetime format. After sanitizing it, you can insert it directly into the database. To MySQL it may be a 'datetime' data type, but to PHP it is simply a string (just like your entire SQL query is nothing more than a string to PHP).
$timestamp = mysql_real_escape_string($_POST['timestamp']);
You should be able to safely insert that into your database for the timestamp field.
There is a function FROM_UNIXTIME in mysql. Why don't you want to use it?

format mysql timestamp using php

i have column named postDate defined as timestamp.
when i print it directly:
echo $result['postDate'];
i do get that what is stored(eg. 2011-03-16 16:48:24)
on the other hand when i print it through date function:
echo date('F/j/Y',$result['postDate'])
i get December/31/1969
what am i doing wrong?
many thanks
try this.
date('F/j/Y',strtotime($result['postDate']));
as timestamp is required, not formatted date as second parameter.
or you can also try
SELECT UNIX_TIMESTAMP(postDate) as postDateInt from myTable
instead of SELECT postDate from myTable
and then have this in your code.
date('F/j/Y',$result['postDateInt']);
The PHP date function looks for an int time() as the 2nd param. Try using strtotime()
echo date('F/j/Y', strtotime($result['postDate']) );
Why not format the date as needed in your MySQL query?
SELECT DATE_FORMAT(postDate, '%M/%D/%Y') as date from table
The PHP `date()' function expects a number for the second parameter - ie a unix timestamp.
You can convert a SQL date string (or virtually any other date string) into a timestamp in PHP by using the strtotime() function. At least two other answers have already suggested this.
However, I would suggest that you'd be better off getting the date out of your database in unix timestamp format in the first place. You can do this by querying using the MySQL UNIX_TIMESTAMP() function, as follows:
SELECT UNIX_TIMESTAMP(mydatefield) AS mydatefield_timestamp FROM mytable
..obviously, replacing the field and table names as appropriate.
Then you will get the date in timestamp format in your returned dataset in PHP, which you can pass directly into the date() function as follows:
echo date('F/j/Y',$result['mydatefield_timestamp']);
Hope that helps.

Categories