apologies this is probably a simple question - I am using php and JS to create a counter and I have stored a time using an SQL time field in my DB- I run a query to return this time but I now wish to convert this time into an integer, I assume I need to use the following, but I am lost on the syntax:
http://www.electrictoolbox.com/using-strtotime-with-php/
any help would be appreciated. many thanks in advance
It's hard to tell from your question what exactly you mean by "an SQL time field."
MySQL offers four kinds of time-like data types: TIMESTAMP, DATETIME, TIME, and DATE. To some extent it matters which one your table contains.
It's also hard to tell what you mean by "convert this time into an integer." Do you mean a UNIX-style timestamp (number of seconds since 1-Jan-1970 00:00:00 UTC)?
If that's the case you can get your database to do this conversion: use
SELECT UNIX_TIMESTAMP(value) ...
in your query. That will work for all the time-like datatypes except TIME. (Strange, eh? TIME means time of day with no date, so that's why it doesn't work.)
Otherwise, without more information it's hard to tell you how to use php to do this: we can't tell what your converting from and what you're converting to.
Related
I've seen this post already, and it didn't quite shed much light on what is going on.
I have a mongo server, that stores information about classes, what times and days they meet and what not. I also have an express server, that interacts with and returns this data.
When I look at the data in Robo3T (a mongo data viewer), it is formatted - as it should be - like so:
2018-09-07 04:00:00.000Z
But when the data comes back to the server, it comes back like this: 2018-09-07T04:00:00.000Z
What is causing this? In no way do i make any attempt to format this data before I display it. I also checked the server output, which returns it the same way:
I guess my question is, why is this happening? and is this impacting my ability to query results from mongo based on a date range? Any assistance would be much appreciated, thank you.
Robo 3T just happens to display dates that way. This does not mean that it actually is stored that way. When you switch the view to "text mode", you will see that it actually is ISODate("2018-09-07T04:00:00.000Z") (with the T).
This format is actually the date format string that is used in JavaScript. And yes, the T is required. See What are valid Date Time Strings in JavaScript?
Simple Date question here, but I can't seem to find a simple answer.
I am storing the 'negative' value of a timestamp in my database like so (they are stored as numbers, not strings):
user-1
--date: -1495255666921
user-2
--date: -1495255666341
I do this for sorting purposes, but that's a separate topic.
When it comes time to read these dates under each user, I want to get the 'positive' version of the timestamp.
I know I can toString() the date, check for the - character, remove it, then convert it back to a Date() (which I then have to run through another function), but that seems inefficient when sending thousands of records back to the client.
Is there a magical way I can poof - get rid of that - and maintain it's datatype as timestamp programatically? Any input or recommendation is appreciated!
UPDATE - Since multiple people have mentioned, this is is the 'bigger' issue I'm dealing with and why I've chosen this sorting method
One of our programmers decided to use a DATE field in the MySQL db in order to achieve this.
Sending and saving a JS date object did work well until the daylight saving changes intervened (with nasty effects :) ).
Of course, saving the date in a DATETIME field solves it, but everybody sees the time/dates in their own timezone.
We need everybody (all over the timezones) to see the same date!
I clarify this, to get the proper answers:
I want to keep using the DATE field storage type in MySQL (vs DATETIME - ok, maybe too much of an optimization, but it's already there and I want a long term solution for when I receive such structure/code from other developers)
Sending local time (local JS in browser) 23-05-2016, will reach the server as 22-05-2016 0X:X0:00Z (UTC) and be store as such. Because it's a DATE field, the stored value will become 22-05-2016 only. And you lost a day! :)
Our solution from bellow not only fixes the DATE field trimming, but also adds the fact that people now can see the same correct date (23-05-2016) no matter of the timezone they are in!
I like the outcome and would love to see some better solutions to achieve the same and improve the system.
Actually, we have noticed the problem only when the daylight saving time changed, so my solution (as answer bellow) is a good solution for that as well. And it only consumes resources client-side.
I have posted my own solution to this question as an answer bellow.
It would be really cool to see a much better solution from you!
With Javascript
Save your dates in ISO format (including timezone information) and use moment.js to convert the datetime to another timezone.
If moment.js is not already a dependency, and you want to avoid extra libraries, keep reading.
With MySQL
Instead of solving this problem when you write the data (losing timezone information in the process), solve it when you read the database.
In your SELECT query, normalize all DATETIME values to your preferred timezone using the convert_tz built-in function.
MomentJs is your best bet. Find the timezone you want and pass the ISO string to it and you should be good to go.
http://momentjs.com/timezone/docs/#/using-timezones/
A DATE is just a year, month, and day. It doesn't have a time, or a time zone. Think about your birthday or your wedding date, or today's date.
The JS Date object is not this at all. It's a timestamp. It's the number of milliseconds elapsed since Midnight January 1st 1970 UTC.
You should leave your date as a date-only wherever possible. Use the ISO-8601 date-only format, which is YYYY-MM-DD. If you have to assign it a time and time zone, then be very careful when you do.
If you just assign midnight local time, then you're risking losing a day (as you showed), and you're not considering that there are local days in some time zones where midnight does not exist! (Such as the spring-forward day in Brazil). Noon is a safer bet than Midnight, but still you should use this sparingly. The better approach is to keep dates as dates, not as date-times.
Also, I'd answer with code if I could, but you didn't provide any code in your question showing what was broken. Please read How do I ask a good question? and How to create a Minimal, Complete, and Verifiable example. Thanks.
There are more solutions to this, but the fastest and easiest that I could come up with is described bellow:
Let's intervene as early as possible in the information stream.
Just change the data before transmitting it through AJAX.
The function we used is this:
function addTimezoneDiffAnd12HoursToDate(date) {
var timezoneOffset = date.getTimezoneOffset();
date.setHours(12-Math.floor(timezoneOffset/60));
date.setMinutes(-timezoneOffset % 60);
return date;
}
What it does is that it converts a Date to be always at noon (12:00) UTC!
You can use it like this:
$scope.contract.contractDate = addTimezoneDiffAnd12HoursToDate($scope.contract.contractDate);
and send it as such to be stored in the DATE field.
Let me know if you have a simpler solution. I'd like to see it.
I'm using FormatJS library along with Handlebars to display a list of events that occured in the past. I'm calling for an endpoint on my server's REST API which returns me the list of events in Json, with datetimes to display for each event. ATM I'm saving datetimes in the DB using GMT time zone.
So when I'm getting my Json, I'm handling datetimes like this :
{{formatRelative commentDate}}
My issue is, since the datetimes are stocked in GMT, they display also like that. For example, since I'm on a GMT+2 timezone, as soon as a new event is created and shows up on the list, I see it "happened 2 hours ago" while it should be "a few seconds ago".
So, is there a way I can handle this ? Am I making a mistake in saving datetimes in GMT in my DB, and if so, how would you handle datetimes coming from different timezones and displaying them to people in other timezones ?
Of course I could customize the formatRelative helper to play with getTimezoneOffset and get the wanted result, but I wanted to know if there is something better to do.
Thanks a lot ahead !
The key to understanding your question is what you wrote in the comments:
Getting the Json, containing datetimes in the format 2016-02-28 10:15:53 - that's UTC time
You should ensure the value in JSON is in full ISO8601 format, including the appropriate offset or Z character to indicate UTC: 2016-02-28T10:15:53Z
Without the offset, most implementations will consider the value to be represented in local time, which explains your results.
Thus, the problem is with your server-side code, not your JavaScript code. There may be a client-side workaround you could apply when the date string is parsed from JSON, but really the best solution would be to qualify it at the server.
In my application i allow user to set a date using a date-picker component.
My issue is when trying to convert string date to UTC/ISO date format the conversion is not happening properly, see the below example.
Example:
User Selected String Date : 01/09/2015 (DD/MM/YYYY)
While im using moment.js to convert the above date to native JS date, See below:
moment(req.body.datePicker,'DD/MM/YYYY')
All good till here, but when the data stored in db the date is getting reduced by 1 day. I have no idea where its getting messed up.
I have managed to create a re-producable scenario using jsfiddle-example please have a look for a better understanding.
My assumption:
when i see the db collection the date is getting stored with a default time: 18:30:00.00Z
this could be one of the reason why the dates are getting changed.
Your problem is timezone.
In my case 01/09/2015 gives 2015-01-08T23:00:00 which is only -1 hour since my timezone is GMT+1
Finally after doing some research i myself found the solution or a hack to fix this issue, it may not be the correct way of doing it but for the current scenario it worked like a charm.
Solution:
All i did was just created a full ISO/UTC date string hard-coding the time to zero. moment(req.body.datePicker,'DD/MM/YYYY').format('YYYY-MM-DD HH:mm:ss.000').toString()+'Z' by doing this the default time will always set to Zero and since the string is a fully qualified ISO/UTC standard format, mongoDB will not try to alter it.
Working example:
http://jsfiddle.net/r42jg/1004/
If any one has a better solution, the please post here so we can improvise this better.