I would like to query a JSON object containing a MySQL TIMESTAMP named 'time':
SELECT time, JSON_OBJECT('t', time, 'v', value) AS value FROM values
But unfortunately, MySQL transforms the ISO 8601 formatted timestamp "2019-04-04T12:00:00.000Z" automatically into this presentation "2019-04-04 12:00:00.000000". See the following response:
{
"time": "2019-04-04T12:00:00.000Z",
"value": {
"t": "2019-04-04 12:00:00.000000",
"v": 30
}
}
Is it possible to access time keeping its original type and presentation (as "2019-04-04T12:00:00.000Z") inside a JSON object? What is the recommended and clean approach to this?
You can use DATE_FORMAT() to make an ISO 8601 format date in an expression.
See Format date in MySQL SELECT as ISO 8601
In your case:
SELECT DATE_FORMAT(time, '%Y-%m-%dT%TZ'),
JSON_OBJECT('t', DATE_FORMAT(time, '%Y-%m-%dT%TZ'), 'v', value) AS value
FROM values
Or alternatively:
SELECT v.time_8601, JSON_OBJECT('t', v.time_8601, 'v', v.value) AS value
FROM (SELECT DATE_FORMAT(time, '%Y-%m-%dT%TZ') AS time_8601, value FROM values) AS v
Re your comment:
https://dev.mysql.com/doc/refman/8.0/en/datetime.html says:
MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format.
The non-hacky way is to use that format. If you want to use a different format (even an ISO format), you must use the DATE_FORMAT() and STR_TO_DATE() functions.
There's a function GET_FORMAT() that returns the format string for some popular choices. But it doesn't support ISO 8601 format (that's noted specifically in the manual, as though this question has come up before).
-- formats in ISO 9075 like '%Y-%m-%d %H:%i:%s', NOT ISO 8601
DATE_FORMAT(time, GET_FORMAT(DATETIME, 'ISO'))
Related
Is there a way to convert a string such as "-1 week" or "-5 minutes" into a datetime value in MySQL similar to php's extremely convenient strtotime() function?
I have a table that stores a human-readable time interval (such as "2 minutes") in one column and a datetime in another column.
I would like to select the rows where more than the amount of time specified in interval has elapsed since datetime.
MySQL doesn't have an equivalent of PHP's strtotime() in the sense that there is nothing that will automatically attempt to parse and determine the format of a date string using by assuming multiple formats.
What it does have is STR_TO_DATE(str,format) which requires you specify the format of your date, time or date + time string. It is the equivalent of PHP's date_create_from_format(format, str) function (though the format of the format parameter are different).
Here are some examples given from the MySQL documentation. They show a date being passed along with the format string that lets it know how the date string is to be interpreted:
SELECT STR_TO_DATE('01,5,2013','%d,%m,%Y');
SELECT STR_TO_DATE('May 1, 2013','%M %d,%Y');
Alternatively, you can cast a string to a date, time or datetime type, but they require a specific format (YYYY-MM-DD hh:mm:ss.fraction) for it to work:
SELECT CAST("2019-11-21" AS DATE);
If you deviate too far from that format it will make a few assumptions but could produce an incorrect date.
I have a dateformat but to display on front end I would like to display the data like so.
SELECT STR_TO_DATE('5,2013','%m,%Y');
The result I would like to generate is 'May 2013'.
Why are you storing dates as string values? Mysql has dedicated data types for date and time values: https://dev.mysql.com/doc/refman/5.7/en/date-and-time-types.html
When using date, you can easily use DATE_FORMAT and set %m,%Y as formatting (second argument).
SELECT replace(date_format(str_to_date('5,2013','%m,%Y'),'%M-%Y'),'-',' ');
As to the format just read the docs: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format. You need an uppercase M for the month name. And use DATE_FORMAT to get from a date to a string.
SELECT DATE_FORMAT(DATE '2013-05-01', '%M %Y');
Assuming that you have 5,2013 stored in your database, you need to use DATE_FORMAT after parsing the string:
SELECT DATE_FORMAT(STR_TO_DATE('5,2013','%m,%Y'), '%b %Y')
Why? Because it seems you don't have a date type stored in the database. So you parse it to date using STR_TO_DATE. This give you the default date format. DATE_FORMAT let you apply other formattings on it.
All avaliable formatting values are documented here: https://www.w3schools.com/sql/func_mysql_str_to_date.asp
In general, I would recommend to think about storing date objects instead of custom date strings like 5,2013. This avoids those castings, because you could directly use DATE_FORMAT. It also has benefits on filtering/ordering and performance. Using date types, you could easily sort by it or filter e.g. everything in month X.
I don't say its not possible with custom strings like 5,2013 but would be more complex and could result in bad performance if the db grows.
You can use the functions:
str_to_date() to convert the string (after concatenating the prefix '1' to your string) to a valid date and then
date_format() to reformat the date:
SELECT date_format(str_to_date(concat('1,', ?),'%d,%m,%Y'), '%b %Y');
Replace ? with your string.
See the demo.
Result:
May 2013
Is it possible to use the FROM_UNIXTIME method in a MySQL INSERT INTO statement, like below?
INSERT INTO mycapacity (timeint, time, datetime) VALUES (FROM_UNIXTIME(20191120085412, '%D %M %Y %h:%i:%s %x'), '20 Nov 2019 16:54:12 GMT', '2019-11-20 08:54:12');
If so, does FROM_UNIXTIME have to be in quotes as the column type is varchar?
MySQL prefers everything to be in ISO 8601 format, or YYYY-MM-DD HH:MM:SS and not some arbitrary text. Use native DATE, DATETIME columns for storing the data.
FROM_UNIXTIME() emits it in the correct format, that should be fine without the format specifier. It's worth noting that this function takes UNIX Epoch Time values only, not arbitrary date strings like 20191112... which is not valid. The time right now is 1574274411 for example.
If you have an integer-encoded date-time value then FROM_UNIXTIME will not help and you'll have to parse it using STR_TO_DATE, as in:
STR_TO_DATE('2019112', '%Y%m%d')
It's not clear exactly what's going on in that number, mind you, so the format of the remainder will need to be addressed with additional specifiers, if it even can be.
Keep in mind any columns with names that are reserved keywords must be escaped:
INSERT INTO mycapacity (timeint, `time`, `datetime`) VALUES (...)
It's far from clear in your question what format you're intending to use for each column, so specifying the schema would help narrow down an answer.
I am pretty new to MySQL, and am looking at a table (through a query) that has three date fields. However, they appear to be in seconds (but I could be wrong), but ultimately, I need to convert them to a valid date/time.
The numbers are:
1366272682
1366239600
1366272682
I think one of these dates is 18th April 2013.
Can someone let me know how I can convert them within the query (or indeed if I am right).
Thank you.
Those "numbers" are actually Unix Timestamps. Use FROM_UNIXTIME() to convert them into human friendly formats:
Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format, depending on whether the function is used in a string or numeric context.
For example:
SELECT FROM_UNIXTIME(1366272682, '%e%D %M %Y')
is there mySQL function to convert a date from format dd.mm.yy to YYYY-MM-DD?
for example, 03.09.13 -> 2013-09-03.
Since your input is a string in the form 03.09.13, I'll assume (since today is September 3, 2013) that it's dd.mm.yy. You can convert it to a date using STR_TO_DATE:
STR_TO_DATE(myVal, '%d.%m.%y')
Then you can format it back to a string using DATE_FORMAT:
DATE_FORMAT(STR_TO_DATE(myVal, '%d.%m.%y'), '%Y-%m-%d')
Note that the year is %y (lowercase "y") in STR_TO_DATE and %Y (uppercase "Y") in DATE_FORMAT. The lowercase version is for two-digit years and the uppercase is for four-digit years.
Use
SELECT CONCAT(
'20',
SUBSTR('03.09.13', 7, 2),
'-',
SUBSTR('03.09.13', 4, 2),
'-',
SUBSTR('03.09.13', 1, 2))
Fiddle demo.
More about formats you can read in the corresponding manual page.
Tip: if this is about conversion value from non-datetime field - better to use DATE/DATETIME data type instead. However, this is a bad idea to operate with dates via string functions. Above there is a nice trick with STR_TO_DATE (will not repeat that code, updated to fit better)
Dates are stored using an internal format. You can use the function date_format() to convert it to a string using a variety of formats. For yours in particular:
select date_format(`date`, '%Y-%m-%d')