MYSQL Date field showing random numbers, how to work out date? - mysql

I've exported a database (I need the data for a report) we have a 'start date' which is the start date of each project, but in MYSQL it isn't showing a date but instead a random number, it must say the date in some way because the tasks seem to go in order and the numbers change accordingly.
Can anybody tell me how to work out the date from the numbers, an example is below:
1337156712
and another:
1321443614
Any help will be great thanks!
OK I am using this PHP script to change the dates:
<?php
$TimeStamp = "1185422400";
$Time = date("m-d-Y", $TimeStamp);
echo $Time;
?>
Can somebody help me turn it into an array so I can include around 500 dates and convert them all at once?
Thanks
Ricky

Assuming your number is a Unix timestamp, FROM_UNIXTIME() will give you a formatted date you can use with DATETIME fields:
mysql> SELECT FROM_UNIXTIME(1321443614) AS time;
+---------------------+
| time |
+---------------------+
| 2011-11-16 11:40:14 |
+---------------------+
1 row in set (0.00 sec)
There are plenty of other time functions available, all of which are listed here.

those are unix timestamps. They are the number of seconds past since Jan 1, 1970. There are a variety of function calls you can user to turn them into dates :)
I will be right back with a way to do it :)
select from_unixtime(1321443614) as time
arg! someone beat me to it!

Related

reformat date into a numeric MDY value in MySQL

I have a column in a table that has dates, as such:
2010-01-15 00:00:00
2002-10-24 09:00:00
2015-04-29 10:00:00
and now I need to generate a new column as such (month, date, year):
01152010
10242002
04292015
I can't find an easy way to do this. All the solutions I've looked at are either for changing date type or getting seconds since epoch!
I've also tried all sorts of substring operations
You could try using the MySQL DateFormat Function.
The documentation is pretty a good resource for this sort of thing.
SELECT DATE_FORMAT(dateColumn, '%m%d%Y') As FormattedDate FROM <table>;
Here is an example I made using SQLFiddle.

Need help developing SQL to find difference in date

I am attempting to write a query that will take a date value and return a numerical value. What I plan to use this for is to track the days until an inspection is due. For example I will input the inspection expiration date into the database, then I want the query to return the value of days remaining until the inspection is due.
Thanks for the help. I am not that good with SQL. I know how to write basic queries but anything past that I really don't know what to do.
You can use timestampdiff() function to get the remaining days.
Lets say the expire date is 2014-10-31 and comparing with now you can get the days as
mysql> select timestampdiff(day,now(),'2014-10-31') as days ;
+------+
| days |
+------+
| 11 |
+------+
1 row in set (0.00 sec)

How to store a datetime in MySQL with timezone info

I have thousands of photos that were taken in Tanzania and I want to store the date and time each photo was taken in a MySQL database. The server, however, is located in the U.S. and I run into problems when I try to store a Tanzanian date-time that falls within the "invalid" hour during spring Daylight Savings time (in the U.S.). Tanzania doesn't do DST, so the time is an actually valid time.
Additional complications are that there are collaborators from many different timezones who will need to access the date-time values stored in the database. I want them to always come out as Tanzanian time and not in the local times that various collaborator are in.
I'm reluctant to set session times because I know that there will be problems when someone sometime forgets to set a session time and gets the times out all wrong. And I do not have authority to change anything about the server.
I've read:
Daylight saving time and time zone best practices and
MySQL datetime fields and daylight savings time -- how do I reference the "extra" hour? and
Storing datetime as UTC in PHP/MySQL
But none of them seems to address my particular problem. I'm not an SQL expert; is there a way to specify timezone when setting DATETIMEs? I haven't seen one. Otherwise, any suggestions on how to approach this issue is greatly appreciated.
Edit:
Here's an example of the problem I'm running into. I send the command:
INSERT INTO Images (CaptureEvent, SequenceNum, PathFilename, TimestampJPG)
VALUES (122,1,"S2/B04/B04_R1/IMAG0148.JPG","2011-03-13 02:49:10")
And I get the error:
Error 1292: Incorrect datetime value: '2011-03-13 02:49:10' for column 'TimestampJPG'
This date and time exists in Tanzania, but not in the U.S., where the database is.
You said:
I want them to always come out as Tanzanian time and not in the local times that various collaborator are in.
If this is the case, then you should not use UTC. All you need to do is to use a DATETIME type in MySQL instead of a TIMESTAMP type.
From the MySQL documentation:
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.)
If you are already using a DATETIME type, then you must be not setting it by the local time to begin with. You'll need to focus less on the database, and more on your application code - which you didn't show here. The problem, and the solution, will vary drastically depending on language, so be sure to tag the question with the appropriate language of your application code.
None of the answers here quite hit the nail on the head.
How to store a datetime in MySQL with timezone info
Use two columns: DATETIME, and a VARCHAR to hold the time zone information, which may be in several forms:
A timezone or location such as America/New_York is the highest data fidelity.
A timezone abbreviation such as PST is the next highest fidelity.
A time offset such as -2:00 is the smallest amount of data in this regard.
Some key points:
Avoid TIMESTAMP because it's limited to the year 2038, and MySQL relates it to the server timezone, which is probably undesired.
A time offset should not be stored naively in an INT field, because there are half-hour and quarter-hour offsets.
If it's important for your use case to have MySQL compare or sort these dates chronologically, DATETIME has a problem:
'2009-11-10 11:00:00 -0500' is before '2009-11-10 10:00:00 -0700' in terms of "instant in time", but they would sort the other way when inserted into a DATETIME.
You can do your own conversion to UTC. In the above example, you would then have '2009-11-10 16:00:00' and '2009-11-10 17:00:00' respectively, which would sort correctly. When retrieving the data, you would then use the timezone info to revert it to its original form.
One recommendation which I quite like is to have three columns:
local_time DATETIME
utc_time DATETIME
time_zone VARCHAR(X) where X is appropriate for what kind of data you're storing there. (I would choose 64 characters for timezone/location.)
An advantage to the 3-column approach is that it's explicit: with a single DATETIME column, you can't tell at a glance if it's been converted to UTC before insertion.
Regarding the descent of accuracy through timezone/abbreviation/offset:
If you have the user's timezone/location such as America/Juneau, you can know accurately what the wall clock time is for them at any point in the past or future (barring changes to the way Daylight Savings is handled in that location). The start/end points of DST, and whether it's used at all, are dependent upon location, so this is the only reliable way.
If you have a timezone abbreviation such as MST, (Mountain Standard Time) or a plain offset such as -0700, you will be unable to predict a wall clock time in the past or future. For example, in the United States, Colorado and Arizona both use MST, but Arizona doesn't observe DST. So if the user uploads his cat photo at 14:00 -0700 during the winter months, was he in Arizona or California? If you added six months exactly to that date, would it be 14:00 or 13:00 for the user?
These things are important to consider when your application has time, dates, or scheduling as core function.
References:
MySQL Date/Time Reference
The Proper Way to Handle Multiple Time Zones in MySQL (Disclosure: I did not read this whole article.)
MySQL stores DATETIME without timezone information. Let's say you store '2019-01-01 20:00:00' into a DATETIME field, when you retrieve that value you're expected to know what timezone it belongs to.
So in your case, when you store a value into a DATETIME field, make sure it is Tanzania time. Then when you get it out, it will be Tanzania time. Yay!
Now, the hairy question is: When I do an INSERT/UPDATE, how do I make sure the value is Tanzania time? Two cases:
You do INSERT INTO table (dateCreated) VALUES (CURRENT_TIMESTAMP or NOW()).
You do INSERT INTO table (dateCreated) VALUES (?), and specify the current time from your application code.
CASE #1
MySQL will take the current time, let's say that is '2019-01-01 20:00:00' Tanzania time. Then MySQL will convert it to UTC, which comes out to '2019-01-01 17:00:00', and store that value into the field.
So how do you get the Tanzania time, which is '20:00:00', to store into the field? It's not possible. Your code will need to expect UTC time when reading from this field.
CASE #2
It depends on what type of value you pass as ?. If you pass the string '2019-01-01 20:00:00', then good for you, that's exactly what will be stored to the DB. If you pass a Date object of some kind, then it'll depend on how the db driver interprets that Date object, and ultimate what 'YYYY-MM-DD HH:mm:ss' string it provides to MySQL for storage. The db driver's documentation should tell you.
All the symptoms you describe suggest that you never tell MySQL what time zone to use so it defaults to system's zone. Think about it: if all it has is '2011-03-13 02:49:10', how can it guess that it's a local Tanzanian date?
As far as I know, MySQL doesn't provide any syntax to specify time zone information in dates. You have to change it a per-connection basis; something like:
SET time_zone = 'EAT';
If this doesn't work (to use named zones you need that the server has been configured to do so and it's often not the case) you can use UTC offsets because Tanzania does not observe daylight saving time at the time of writing but of course it isn't the best option:
SET time_zone = '+03:00';
Beginning with MySQL 8.0.19, you can specify a time zone offset when inserting TIMESTAMP and DATETIME values into a table.
The offset is appended to the time part of a datetime literal, with no intervening spaces, and uses the same format used for setting the time_zone system variable, with the following exceptions:
For hour values less than 10, a leading zero is required.
The value '-00:00' is rejected.
Time zone names such as 'EET' and 'Asia/Shanghai' cannot be used; 'SYSTEM' also cannot be used in this context.
The value inserted must not have a zero for the month part, the day part, or both parts. This is enforced beginning with MySQL 8.0.22, regardless of the server SQL mode setting.
EXAMPLE:
This example illustrates inserting datetime values with time zone offsets into TIMESTAMP and DATETIME columns using different time_zone settings, and then retrieving them:
mysql> CREATE TABLE ts (
-> id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> col TIMESTAMP NOT NULL
-> ) AUTO_INCREMENT = 1;
mysql> CREATE TABLE dt (
-> id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> col DATETIME NOT NULL
-> ) AUTO_INCREMENT = 1;
mysql> SET ##time_zone = 'SYSTEM';
mysql> INSERT INTO ts (col) VALUES ('2020-01-01 10:10:10'),
-> ('2020-01-01 10:10:10+05:30'), ('2020-01-01 10:10:10-08:00');
mysql> SET ##time_zone = '+00:00';
mysql> INSERT INTO ts (col) VALUES ('2020-01-01 10:10:10'),
-> ('2020-01-01 10:10:10+05:30'), ('2020-01-01 10:10:10-08:00');
mysql> SET ##time_zone = 'SYSTEM';
mysql> INSERT INTO dt (col) VALUES ('2020-01-01 10:10:10'),
-> ('2020-01-01 10:10:10+05:30'), ('2020-01-01 10:10:10-08:00');
mysql> SET ##time_zone = '+00:00';
mysql> INSERT INTO dt (col) VALUES ('2020-01-01 10:10:10'),
-> ('2020-01-01 10:10:10+05:30'), ('2020-01-01 10:10:10-08:00');
mysql> SET ##time_zone = 'SYSTEM';
mysql> SELECT ##system_time_zone;
+--------------------+
| ##system_time_zone |
+--------------------+
| EST |
+--------------------+
mysql> SELECT col, UNIX_TIMESTAMP(col) FROM dt ORDER BY id;
+---------------------+---------------------+
| col | UNIX_TIMESTAMP(col) |
+---------------------+---------------------+
| 2020-01-01 10:10:10 | 1577891410 |
| 2019-12-31 23:40:10 | 1577853610 |
| 2020-01-01 13:10:10 | 1577902210 |
| 2020-01-01 10:10:10 | 1577891410 |
| 2020-01-01 04:40:10 | 1577871610 |
| 2020-01-01 18:10:10 | 1577920210 |
+---------------------+---------------------+
mysql> SELECT col, UNIX_TIMESTAMP(col) FROM ts ORDER BY id;
+---------------------+---------------------+
| col | UNIX_TIMESTAMP(col) |
+---------------------+---------------------+
| 2020-01-01 10:10:10 | 1577891410 |
| 2019-12-31 23:40:10 | 1577853610 |
| 2020-01-01 13:10:10 | 1577902210 |
| 2020-01-01 05:10:10 | 1577873410 |
| 2019-12-31 23:40:10 | 1577853610 |
| 2020-01-01 13:10:10 | 1577902210 |
+---------------------+---------------------+
Note:
Sadly, the offset is not displayed when selecting a datetime value, even if one was used when inserting it.
The range of supported offset values is -13:59 to +14:00, inclusive.
Datetime literals that include time zone offsets are accepted as parameter values by prepared statements.
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.)
You can't... you will find a lot of answers saying you "it is not necessary, store using UTC", but it is: you need to store datetimes with the timezone and MySQL can't...
I worked last 10 years in Postgres and all this kind of problems doesn't exist (date times and timezones are managed with no friction, you can store and compare datetimes expressed in different time zones transparently, the ISOString format is managed naturally,etc...).
I actually work in MariaDB and I can't understand why in 2022, in a globalized world, MySQL continues not supporting per value timezones.
I once also faced such an issue where i needed to save data which was used by different collaborators and i ended up storing the time in unix timestamp form which represents the number of seconds since january 1970 which is an integer format.
Example todays date and time in tanzania is Friday, September 13, 2019 9:44:01 PM which when store in unix timestamp would be 1568400241
Now when reading the data simply use something like php or any other language and extract the date from the unix timestamp. An example with php will be
echo date('m/d/Y', 1568400241);
This makes it easier even to store data with other collaborators in different locations. They can simply convert the date to unix timestamp with their own gmt offset and store it in a integer format and when outputting this simply convert with a

Simple creation of table and inserting value to it

I Want to create a table in MySql for which has a column for Time
Value for time column must accept like 9AM to 10PM
+-----------------------------+
| DATE |
+-----------------------------+
| 9AM to 10PM |
+-----------------------------+
Which datatype should i use ?
If i don't want to use varcar & If i can use TIME data-type- How to represent values there ?
I am looking for create table and insert statement as an answer for above specifications ?
I am a newbie so please go easy with answers
Thanks !
As suggested above in comment the table structure would be:
Create Table YourTable
(
FromTime Time,
ToTime Time
)
Now Insert values as below:
Insert into yourTable
VALUES(TIME(STR_TO_DATE('09:00 AM', '%h:%i %p')),TIME(STR_TO_DATE('10:00 PM', '%h:%i %p')))
Use Time Data Type to save Time.
You can not insert 9AM to 10PM in datetime datatype column.
you have to use datatype whose representation should be like string, like varchar.
It's hard to tell exactly what you need based on what you've described - if you could provide a little more context we might be able to offer you more insight?
But as #rkp has mentioned, if you want the time interval to be represented as "9AM to 10PM", you will have to use some form of string/text field e.g. varchar
Alternatively, depending on how you plan to use this data, you could also use two fields - one for start time and one for end time. It would probably then be recommended that you use a datetime field since this will allow for much more flexibility (e.g. when calculating differences between time periods etc)
For reference - these are your options:
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-types.html

Storing a date where only the year may be known

What's the best way to store a date value for which in many cases only the year may be known?
MySQL allows zeros in date parts unless the NO_ZEROES_IN_DATE sql mode is enabled, which isn't by default. Is there any reason not to use a date field where if the month and day may be zero, or to split it up to 3 different fields for year, month and day (year(4), tinyint, tinyint)?
A better way is to split the date into 3 fields. Year, Month, Day. This gives you full flexibility for storing, sorting, and searching.
Also, it's pretty trivial to put the fields back together into a real date field when necessary.
Finally, it's portable across DBMS's. I don't think anyone else supports a 0 as a valid part of a date value.
Unless portability across DBMS is important, I would definitely be inclined to use a single date field. If you require even moderately complex date related queries, having your day, month and year values in separate fields will become a chore.
MySQL has a wealth of date related functions - http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html. Use YEAR(yourdatefield) if you want to return just the year value, or the same if you want to include it in your query's WHERE clause.
You can use a single date field in Mysql to do this. In the example below field has the date data type.
mysql> select * from test;
+------------+------+
| field | id |
+------------+------+
| 2007-00-00 | 1 |
+------------+------+
1 row in set (0.00 sec)
mysql> select * from test where YEAR(field) = 2007;
+------------+------+
| field | id |
+------------+------+
| 2007-00-00 | 1 |
+------------+------+
I would use one field it will make the queries easier.
Yes using the Date and Time functions would be better.
Thanks BrynJ
You could try a LIKE operative. Such as:
SELECT * FROM table WHERE date_feield LIKE 2009;
It depends on how you use the resulting data. A simple answer would be to simply store those dates where only the year is known as January 1. This approach is really simple and allows you to aggregate by year using all the standard built in date functions.
The problem arises if the month or date is significant. For example if you are trying to determine the age of a record in days, weeks, months or if you want to show distribution across this smaller level of granularity. This problem exists any way, though. If you have some full dates and some with only a year, how do you want to represent them in such instances.