Handle a different timezone in mysql - mysql

Long story short, I'm working on a server that has a different time zone to my local area, although the output should be relevant to this local area alone. I wrote a query to see if some record had been stored for 3 or more hours, and that works a treat, however, I'm trying to find a way to re-write it so that it can convert the time to this time zone, prior to comparing.
With my most recent attempt, it looks like it compares the time prior to converting the time, I was just wondering if there’s a way of doing it through mysql, I should probably also mention that I’m currently limited to using version 5.096. Below you can see what I’ve written so far, I only noticed there was a timezone issue once I actually uploaded a file onto my FTP and tested it through that.
If I’m doing something stupidly wrong, please tell me what I’m doing wrong exactly, and if you could provide a solution, it would be much appreciated! Thanks!
SELECT * FROM
(
SELECT *, IF(HOUR(TIMEDIFF(CONVERT_TZ(current_time, '-07:00', '+00:00'), Time)) >= 3, 1, 0) = 1 AS timing
FROM callLogs
WHERE Inqueue = '1'
ORDER BY Time, Inqueue ASC
) AS qry
WHERE qry.timing = '1'
Another thing I should probably point out, I can't use any stored procedures, I'm quite limited in terms of what I can do as it turns out, which is just great! I also tried to contact the hosting company that is being used, and they came back with nothing useful, I think their English is very broken. They weren't answering a simple question.... So... Any ideas? ¯_(ツ)_/¯

Make sure that timezone support is enabled by mysql:
mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
The system is your system timezone, the below query gives time difference between your system and GMT in seconds.
SELECT TIMESTAMPDIFF(
SECOND, TIMESTAMP('2018-02-01 00:00:00'),
CONVERT_TZ(TIMESTAMP('2018-02-01 00:00:00'), 'SYSTEM', 'GMT')
)

Related

Is PHPmyadmin current date based on my computer's localdate?

I'm doing some testing for my system in selecting data between two dates.
so I tried changing my computer's localdate to like year 2020 and run my system, so I'm expecting my CURRENT_DATE is May 10, 2020.
and I wont be getting any rows from my query because all of my data is year 2018
But after I use my query of cur_date() its still selecting those 2018 rows.
so I thought maybe my Phpmyadmin has its own cur_date().
I'm doing this test for my system will be use for the next couple of years. so I want to try and test my queries if today is already 2025 or something.
I thought maybe my Phpmyadmin has its own cur_date().
PhpMyAdmin has nothing to do with it. Your local computer also has nothing to do with it.
When you put CURDATE() in a query, that's part of the query. It's just text, like the SELECT part or the FROM part.
That means it's evaluated by the MySQL server. Just like the data of your rows is retrieved from the server, not from PhpMyAdmin or your local computer.
So the date returned will be that of the MySQL server.
so I want to try and test my queries if today is already 2025 or something.
The way to do this is to take out the expression CURDATE(), and replace it with the "fake" date you wish to use instead.
Something like:
SELECT * FROM `TheTable` WHERE `TheDate` > '2025-01-01';

How do I store time in 12 hour format in mysql

I am developing an application in which user schedules his date, time and event.
I was wondering if there is any possible way that I can store time in hh:mm:ss AM/PM format rather than 24 hour.
I think my question wasn't clear enough , adding some stuff
Problem Definition : Migration from PHP-MSSQL (Windows) web service to PHP-MYSQL (Linux)
Back End was written before y2k its an old program launced as an single platform , prior to me developers ported this program on the web but did not ported the DMS (database management system aka utility for data entry guys) i am not sure about the reason behind this.
Old procedure to enter data , data entry guy used to log in on windows server start the application and enter data.
After migration we can no longer use old DMS program hence i have to write new DMS program.
I asked few question about migration from mssql to mysql before you all can have look here https://stackoverflow.com/questions/22603868/converting-porting-mssql-table-to-mysql-table
Biggest problem that i have facing is data entry guys want their dms just like before not a inch less or more (cant blame them for this).
old dms view
new dms
I am trying my level best to give them old look feel and functionality back as well as wanted to reduce their work since most of the times they have to update an old entry with new dates only , before that they used to do it by deleting whore record and recreation it again.
front end view of date added:
mssql db structure
mysql db structure
You are probably looking for DATE_FORMAT(date,format)
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
You should store dates and times in a database as either a Date, Time or DateTime datatype (depending on what types your db provider supports (MySql reference)). Never store these as a string.
The way the user inputs the value should be determined by their culture settings on the machine:
dateTimePicker1.Format = DateTimePickerFormat.Custom
dateTimePicker1.CustomFormat = Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern
That way if they prefer 12h format, they just set that in control panel
You can get the inputted value like so:
Dim ts As TimeSpan = New TimeSpan(DateTimePicker1.Value.Hour, DateTimePicker1.Value.Minute, DateTimePicker1.Value.Second)
Storing dates and time in the database instead of string makes life a lot easier when you come to read them because you can just format the date or time in any way you wish.
You can then use the same code in your application to show that date or time in the users preferred culture. (Formatting Date and Time for a Specific Culture)
It also allows you to perform queries on the actual date or time which would not be possible (or at least very inefficient) on a string
.ToString("HH:mm") Solved all my problems for a while.

Apply a function on all Select statements on table implicitly - SQL Server

Is it possible to apply some function (user defined / system) to selected columns automatically, may be binding it at schema level.
My scenario is I am saving timestamps of record saving in each table automatically, for which I have used getdate() as default value of those columns, It was working fine till we had our own hosting. But since now we are moving to shared hosting and don't know in which timezone the servers shall be placed in future, I am using GETUTCDATE() to get GMT time.
Since a lot of procedures / functions are already in place, I am looking for something where I don't need to convert this UTC time to my local time explicitly.
So that my Select * from MyTable shall give me time in my fixed timezone using the function I've created.
Let me know if its possible by any way.
Thanks.
It's not exactly clear what you want to do, but there's no way to replace what the SELECT statement asks for with something else: what you ask for in a query is what you get. Unless you replace a table with a view with the same name, but that probably isn't the best approach.
Using a view or function would still mean you have to change your code anyway, so why not just UPDATE all data to UTC time and then do the conversion in your application code? SQL Server has no idea what time zone a client is in anyway, so it isn't possible to do the conversion reliably on the server side. Unless perhaps the client sends the local time zone to the server as a parameter or in CONTEXT_INFO, but there wouldn't be much point because doing it in the client would be simpler anyway.
And of course handling it all in the application will give you a much more flexible, robust solution.

sending terminal/shell command from mysql to terminal and retrieve answer while looping cursor

I'm using php with MySQL on macOS.
I would like to select a large amount of emails from a database and perform a dns lookup for each email in my selection using a dig command from the terminal/shell, something like: "dig gmail.com" .
Of course, I can loop this select through php but it will be very slow compared to looping cursor on MySQL.
How to send terminal commands from mysql to the terminal and retrieve answer on macOS?
You can't execute shell commands from within an SQL query (thank god), or else it would be a horrible security vulnerability... You would have to do it from php.
P.S. It is however possible to execute shell commands from the MySQL command line utility
\! ls
...but if I understand your question, it won't help solve your current problem.
(I'm assuming that you really mean ADDR_SPEC when you're talking about email addresses)
but it will be very slow in compare with looping cursor on mysql
No not really. The only difference is that depending on how you implement this the PHP approach requires that you retrieve the entire result set before you start iterating through it. However breaking this up into smaller result sets is trivial.
Also, the limitation on the performance of your algorithm is the speed of DNS lookups - and that's all about latency - if your objective is to make this go faster then you should be running multple requests in parallel.
The next thing you should consider is that you've probably got multiple mailboxes for each MX, e.g. user1#gmail.com, user2#gmail.com.... While if you've got DNS caching setup properly there will be less overhead than going to the source each time, if you're working with a very large data set or will be doing this more than once, it makes a lot more sense to just work with unique MX host values, e.g.
SELECT DISTINCT SUBSTR(addr_spec FROM LOCATE('#', addr_spec)) AS mx2chk
FROM yourtable
WHERE addr_spec LIKE '%#%'
AND (email_checked IS NULL
OR email_checked<NOW() - INTERVAL 300 DAY )
;
Indeed, if your flagging the data then you can use your own database to verify the MX.
using a dig command from terminal/shell
Please don't tell me that you're running a shell from a PHP controlling process to do a DNS lookup?

grails/mysql timezone change

Whats the best way to accomplish changing the timezone of an app? The way I see it the following must occur:
Server TZ is changed by sys admin
mysql must be restarted.
every time based column in the database must have all values updated, using convert_tz or equivalent. So either a mysql script must be written or a grails script that loads every row for each class, updating all the time fields.
Obviously the server should be taken down while this is happening, and backups must be in place incase of an error.
Is there a better/easier way to do this?
Java does not use time zones when using Dates; it stores everything as UTC and only uses time zones when displaying dates. see the following link for a discussion of java date/time.
http://www.odi.ch/prog/design/datetime.php
If you're using the Date, Time, or DateTime column types in MySQL, time zone does not matter.
If you’re using the TIMESTAMP column type, time zones may matter since the TIMESTAMP is stored as a UTC but has conversion done when both retrieving and storing the values. For a discussion of MySQL time zone behavior see
http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html .
If you’re worried about synchronizing objects across multiple servers in different time zones things get more complicated, see the following thread for a discussion of this.
http://www.pubbs.net/201006/grails/2500-grails-user-how-to-get-gorm-to-store-dates-as-timestamp-in-utc-by-default-without-a-custom-hibernate-mapping-or-joda-time-plu.html
I know this is an old question but I think it's also pretty timeless... at least, I have stumbled upon it a fair number of times recently... so I thought I would contribute my solution.
First, I am using Grails 2.5.1 and PostgreSQL 9.4 as the backend.
Second, Date fields in Groovy/Grails are stored as timestamp without time zone in PostgreSQL. So it seems to me the first answer above is not actually fully correct - the date is not stored in UTC. This observation got me thinking... along the lines of "well if the database doesn't know what the timezone is, who does"? And the first answer that came to mind was "maybe it's Spring".
Third, the specifics of my problem is that I have a lot of dates that I bootstrapped into the database via BootStrap.groovy and new ThisClass().save(). And because these were dates, not dates + times, they all look like 2005-11-03 00:00:00 as PostgreSQL timestamps (without timezones).
Fourth, what really made the penny drop was when I edited one of my GSPs to include the timezone in the date format string, which showed up as PST (where my server is); and when I included timeZone="Asia/Kolkata" in the g:formatDate of the field in question, the time advanced by 12h30. So pretty clearly my server was running in PST8PDT and since that wasn't PostgreSQL I came back to Spring as the potential place to change things.
Fifth, after reading a few comments about setting the locale in grails-app/conf/spring/resources.groovy I decided to try setting the locale and timezone there, as per:
// Place your Spring DSL code here
beans = {
// from http://stackoverflow.com/questions/1569446/grails-how-to-change-the-current-locale
localeResolver(org.springframework.web.servlet.i18n.SessionLocaleResolver) {
defaultLocale = new Locale("en","IN")
java.util.Locale.setDefault(defaultLocale)
println "configure spring/resources.groovy defaultLocale $defaultLocale"
defaultTimeZone = TimeZone.getTimeZone("Asia/Kolkata")
java.util.TimeZone.setDefault(defaultTimeZone)
println "configure spring/resources.groovy defaultTimeZone $defaultTimeZone"
}
}
I also used g:format timezone="Asia/Kolkata" format="dd MMM, yyyy a z" for all my date fields. And that seems to interpret all data in PostgreSQL timestamp fields in the correct timezone and at the anticipated hour (ie the hour that was entered), even though the dates were first entered "in the wrong time zone".
Sixth, g:datePicker - I read a number of posts about making this "time zone sensitive", but I found that its dates are interpreted as in the timezone used by Spring and so in my case, this is exactly what I need. Conversely, if someone wanted to enter dates in their locale and have Spring convert them on the fly to the server's time zone, I guess that would require some extra effort.
Personally I think it would be really cool if g:datePicker accepted timeZone as a parameter and used it in the same way g:formatDate does.
We had problems with time differences between using GORM and using groovy.sql.Sql (for quicker data import).
GORM was using the grails config timezone (UTC) that we set in the Bootstrap, but groovy sql was using the default system timezone (GMT).
The problem was solved by setting the timezone in the $JAVA_OPTS, although you could add the switch to grails opts or to the run-app command.
grails -Duser.timezone=UTC run-app