I know that this is longed asked question but still I can't find an answer.
I have a fix time in and out in my database.
Also I have date_in and date_out in separate columns.
All the data in my database come from csv which is in that exact format.
Can I concatenate (time_in and date_in) and (time_out and date_out) and put them in a designated column which is in timestamp format?
I'm making a import and export of csv in which those info below is concern. So far I can export it but
my import doesn't work well. I use the phpmyadmin csv load data to import. Can't get my head in importation of dates and times coz other data mess up in my database.
Note: total_hrs is not included in the csv which means that it is already in my database. And it doesn't have a value so basicaly I will provide values for that in my script.
Example:
id | time_in | time_out | date_in | date_out | total_hrs
1 | 9:30pm | 7:30am | 2013-12-01 | 2013-13-01 | ?
This should have a 10 hours elapsed time.
So basically it also has a different date.
I'm confused whether I need to convert the time in timestamps or something similar to get the time difference or I also need to have the date as well to be a basis in getting the difference between the two time??Any suggestions.
It could be also 34, 58,.. hours. I advise you to store timestamps, if you will need pretty display of it you can just use print (or smth similiar) function in MySql.
If you have the date you should use timestamps. They're easier to compare.
use timestamps in mysql:
INSERT INTO tblTimes (timein) VALUES (NOW());
UPDATE tblTimes SET timeout = NOW() WHERE id=$someid;
to compare, see https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff
Related
I'm writing a script using PHP & MySQL where I can record the shifts I work (HGV driver).
Upon posting the form data PHP calculates shift duration, wages accumulated, overtime, distance driven, etc, and stores it in the MySQL database.
I want to then display all shifts in a table but group them by my pay week which unfortunately starts on a Sunday.
If the pay week was Mon-Sun I wouldn't have this problem as I could use week numbers but I can't due to the week starting on a Sunday.
My code is as follows:
^^^^^^^^^^^^^^^^^^^
// DB Connection //
// Return the earliest shift in the database //
$result = $db->query("SELECT * FROM `shifts` ORDER BY `shift_start` ASC LIMIT 1");
$data = $result->fetch_assoc();
// Establish the previous Sunday //
$week_from = strtotime(date('Y-m-d',mktime(0,0,0,date('m',$data['shift_start']),date('d',$data['shift_start']),date('y',$data['shift_start']))) . 'last sunday');
// PHP Loop Goes Here //
Firstly, is the above code the most efficient way of getting the start date (previous Sunday)?
Secondly, what's the best way to loop through the weeks where there are shifts?
TIA
This is a two part question, so I will try to cover them separately.
Regarding your first question, I would suggest using the MIN() function when selecting the smallest or earliest value in a database, and ensuring you have an index on the "shift_start" column. More information on the difference between MIN() and ORDER BY/LIMIT can be found here.
Then your query would look a something like this:
SELECT MIN(`shift_start`) FROM `shifts`;
Personally, I also find MIN() far more readable.
Now, for the other (and far more complicated) question:
You've not provided much detail on what your database (or the contents) looks like. Since you're using the PHP date function, I am assuming you're saving the timestamps as UNIX instead of MySQL TIMESTAMP/DATETIME types.
Firstly, I would suggest you migrate to using a TIMESTAMP/DATETIME column type. It'll simplify the query you're attempting to run.
If you're unable to change to a TIMESTAMP/DATETIME column, then you can convert a UNIX timestamp to a DATETIME.
MySQL has a YEARWEEK() function that you can use to group by:
SELECT STR_TO_DATE(CONCAT(YEARWEEK(`shift_start`), ' Monday'), '%X%V %W') AS `date`, SUM(`wage`) AS `wage` FROM `shifts` GROUP BY YEARWEEK(`shift_start`);
This will output something similar to:
+------------+------+
| Date | Wage |
+------------+------+
| 2021-11-29 | 50 |
| 2021-12-06 | 15 |
+------------+------+
I'm using Godaddy's MySQL database. Since their timezone is MST UTC -7, I needed to modify my code. I figured out how to do it when using NOW() function. However Im struggling while converting result of CURDATE() to my local date. Topics in the website didnt help it. I dont have privilege to change timezone of mysql since it is shared host. The problem about CURDATE() is, since there is 10 hours difference between server and my country, dates will be different at somepoint.
What I have tried so far
First attempt
SELECT convert_tz(CURDATE(),'-07:00','+03:00')
this query returns following output in the mysql.
convert_tz(CURDATE(),'-07:00','+03:00')
2016-05-14 10:00:00
I didnt try yet since still dates are the same but this code probably done the work. But the problem is about the time comes after date.CURDATE should return only date. I think it returns the differences between two timezones which equals to 10 hours but I think it is gonna cause problem when Im comparing 2 dates.
Second attempt
SELECT convert_tz(CURDATE(),'MST','EEST');
Since server's timezone is MST and my timezone is EEST, I tried in this way but it returns NULL.
The question is what should I do to just return date without that 10:00:00 there. or is there any better way?
There are a couple of problems with your approach.
First, CURDATE() returns a date, not a datetime.
Second, you need to convert the current date and time from the server's time zone to your time zone before truncating the time portion. This means using NOW() inside, not CURDATE().
Third, you need to use the correct abbreviations for the correct time zones for both sides of the conversion, for the entire year. CONVERT_TZ() will return NULL if either time zone is unrecognized.
In this case, MST/MDT is called "MST7MDT" and EET/EEST is called "EET" in the MySQL time zone tables. It's surprising that Go Daddy doesn't set their server clocks to UTC -- that's sort of a de facto standard for server clocks, but assuming not, "MST7MDT" is probably the most correct value.
mysql> SELECT DATE(CONVERT_TZ(NOW(),'MST7MDT','EET'));
+-----------------------------------------+
| DATE(CONVERT_TZ(NOW(),'MST7MDT','EET')) |
+-----------------------------------------+
| 2016-05-14 |
+-----------------------------------------+
1 row in set (0.00 sec)
Or, you could use the more intuitive localized names for the time zones. I believe these values would also be correct, an would accommodate summer and time changes correctly:
mysql> SELECT DATE(CONVERT_TZ(NOW(),'America/Denver','Europe/Bucharest'));
+-------------------------------------------------------------+
| DATE(CONVERT_TZ(NOW(),'America/Denver','Europe/Bucharest')) |
+-------------------------------------------------------------+
| 2016-05-14 |
+-------------------------------------------------------------+
1 row in set (0.00 sec)
Try to convert you date into string using CAST, and then get a substring.
SELECT SUBSTRING_INDEX( CAST(CONVERT_TZ(CURDATE(),'-07:00','+03:00') AS char), ':', -1)
Should return
2016-05-14 10:00
Im using MySQL with PHP, and the project is a kind of notification manager
if some one does some thing, a new notification need to be posted in the common post-ground
the issue is - we have users from multiple timezones, currently Im using "datetime" as the field type, so what ever I enter converts into UTC
for example: Im from India(+5:30) and if I create a notification at 21/3/2015 22:50:00, it is saving in DB as 21/3/2015 17:20:00
storing works perfectly well from all zones, but while retrieving it shows for me as 21/3/2015 17:20:00(UTC) but Im expecting in my timezone(IST +5:30) so what Im expecting is 21/3/2015 22:50:00.
is there a way to mention in the query itself to get the time converted in the fetching itself?
or any other way to convert and process further?
any help on this is greatly appreciated.
Thank you
You can use the function convert_tz so while selecting you can use the following
mysql> select convert_tz('2015-03-21 17:20:00','+00:00','+05:30') as ist_time;
+---------------------+
| ist_time |
+---------------------+
| 2015-03-21 22:50:00 |
+---------------------+
1 row in set (0.00 sec)
All you need to do is to change the hard coded date '2015-03-21 17:20:00' to your column name in the selection.
You can get your client TimeZone through JSTZ
In your php file, you can simply convert the date after you received the from mysql:
$date = new DateTime($date . " " . "UTC");
$date->setTimezone(new DateTimeZone($timeZoneTo));//$timeZoneTo you get it from JSTZ
I have a date that looks like 1003029303, which I guess is what's known as a linux UNIX time stamp.
What format should I save it as in a mysql database? I don't suppose that an int(10) is the right way.
`gottime` int(10)
I take it you are trying to save Birthdays or something similar. DATETIME format is the proper way to store past dates. A unix timestamp should only be used for current day items that do not exceed 30-40 +/- years.
The MySQL DATETIME format is YYYY-MM-DD HH:MM:SS.
I suggest using the DATETIME data type, and then use the FROM_UNIXTIME() and UNIX_TIMESTAMP() functions to convert as required:
SELECT FROM_UNIXTIME(1003029303);
+---------------------------+
| FROM_UNIXTIME(1003029303) |
+---------------------------+
| 2001-10-14 05:15:03 |
+---------------------------+
1 row in set (0.08 sec)
SELECT UNIX_TIMESTAMP('2001-10-14 05:15:03');
+---------------------------------------+
| UNIX_TIMESTAMP('2001-10-14 05:15:03') |
+---------------------------------------+
| 1003029303 |
+---------------------------------------+
1 row in set (0.00 sec)
You shouldn't store UNIX timestamps in your database. Mainly because MySQL (amongst other brands) databases includes DATE functions to calculate most any type of DATE math you can think of. Whereas if you store it as a timestamp, you would have to either, convert the timestamp within mysql first and then format it OR use PHP's date() function.
Timestamps are simply integers. You could store it like that.
You could also use MySQL's TIMESTAMP data type with the FROM_UNIXTIME() and UNIX_TIMESTAMP() functions to convert to and from MySQL's format.
$query = "UPDATE table SET
datetimefield = FROM_UNIXTIME($phpdate)
WHERE...";
$query = "SELECT UNIX_TIMESTAMP(datetimefield)
FROM table WHERE...";
Personally, I store dates in MySQL databases using the DATETIME field type. For example, 2010-07-27 09:30:09.
It's far easier to read than a time stamp, and if you need to convert it to a UNIX timestamp you can do so with PHP's strtotime() function.
I need to save a library all 7 days 'open time' and 'close time'
, Please suggest how to achieve this?
Currently I have create a database table_lib_hours
-----FIELD-----|--TYPE-------
|day_id | int(10) |
|day_name |varchar(100) |
|day_open_time |TIME |
|day_close_time|TIME |
|last_update |TIMESTAMP |
Now my question is
Is there any way to store all 7 day's name in day_name field automatically
?
Use a timestamp in UTC timezone for easier relocation of the server.
In your application, simple format the timestamp for output. When reading in data, use gmmktime().
strftime() with a format of %a or %A will give you the weekday name for a date.
Leave it as a normal time in the database and use strftime() with a format of %I or %l combined with %p or %P when displaying it .
it's usually better to keep non formatted or locale independent data inside your app, and let the front end display/format it...
So I don't know if you have to support multiple language in your app, but if it's the case I'd definitely go with a day of week index instead of the day name.
1) there's usually already functions to handle this in DB engines like DAYOFWEEK() in MySQL.
2) it's easier to order when you query it.
for the time i'd go with what fireeyedboy suggested and use STR_TO_DATE to insert your data in the DB and DATE_FORMAT when you fetch back the data
all the functions you need are here
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html