MYSQL DateTime vs strtotime string held in database - php

I am trying to work out which is the best solution for me - i am making a roster application and have been working with the string, but think it may be beneficial to switch to the datetime type - currently working with dates is getting hard, trying to put the shifts onto a roster without doing a query for every single cell.

If you have something that's a date or a date/time then it's always better to use the right datatype for that. You get many benefits in terms of being able to do functions on it, having comparisons work, etc. It will also map well to the date/time types in your preferred language.

I think storing the dates as a datetime field makes the most sense, but I agree, it's not the easiest to deal with. I have a function in my date library that turns MySQL datetime values into a PHP timestamp.
function datetime_to_timestamp($datetime)
{
$timestamp = strtotime( $datetime );
return $timestamp;
}
Hope that helps.

PHP function strtotime($datetime) converts mysql datetime fields to unix timestamp and works really well. Why using an extra wrapper?

Related

comparing date drectly using Eloquent when date is stored in a different format in a database

I am writing a program that sends emails to users when their subscription is about to expire so i have a table in my database with a date stored in varchar as 12th April 2018 I am using that format because it is easy to read therefore I don't have to convert it again later.. But when i write
$currentdate= Carbon::now()->toDateTimeString();
$threeDaystoExpire =Carbon::now()->addDays(130)->toDateTimeString();
return $expiredPacks = DB::table('subscriptions')
->whereDate('expires_on','>',$currentdate)
->whereDate('expires_on','<=',$threeDaystoExpire)
->get();
I get a blank return output but when i change expires_on to created_at that is formatted like this 2018-04-12 12:41:36 I get the correct output. I tried changing the format of $currentdate and $threeDaystoExpireto match the data in my database as advised by previous threads i read and tried again like this
$currentdate= Date('dS F Y', strtotime(Carbon::now()->toDateTimeString()));
$threeDaystoExpire =Date('dS F Y', strtotime(Carbon::now()->addDays(130)->toDateTimeString()));
return $expiredPacks = DB::table('subscriptions')
->whereDate('expires_on','>',$currentdate)
->whereDate('expires_on','<=',$threeDaystoExpire)
->get();
I get the same empty output. I am currently stuck. All the posts I've read only uses one value so they just make a statement to return just the date, convert it to a timestamp format then compare. I have hundreds of those date and I cant write a statement for each one so any help to tackle this problem will be greatly appreciated.
The toDateTimeString() method converts the Carbon DateTime object into a specific format such as 1975-12-25 14:15:16 which simply isn't a match for your varchar field.
Try using the Carbon API to convert Now to the format you need...
$currentdate = Carbon::now()->format('dS F Y');
$threeDaystoExpire = Carbon::now()->addDays(130)->format('dS F Y');
I'll also point out that the comparison will look at the day first, then the string value of the month, then the numerical year. This will give you very odd results. I might recommend strtotime on the output of your varchar field and use that instead instead of the other way around.
Do yourself a favor and store dates as YYYY-MM-DD (in a date column), it will make your life much easier. It's also easy to read and has been the standard format for ages (for good reasons).
The format you choose for your frontend is a different matter. You can maybe use an accessor for that.
I made a separate field to store the date in a human readable format so I don't have to convert it later in my app, then stored the timestamp format of the same date in a separate field to handle the calculations. It is way easier to use, read and saves me the stress of converting from timestamp then later reconverting back to timestamp which doesn't make sense.
As advised here to leverage platform tools more. I decided that data that will be used in different forms will be stored in a general format and i will allow the platform handle how they want to represent those data.

Storing timestamp in MySQL

I'm grabbing data from a webpage that returns a timestamp in the following form (which is a string):
2013-11-09T15:14:48.957604
How can I interpret this in PHP, and what is the best way to store this in a MySQL database?
The best way to store it is to use the MySQL DATETIME data type. It is specifically meant to handle date/time values, and it works beyond the year 2037, which is the approximate limit using unix timestamps. MySQL and PHP both handle these values with ease using built in functions/libraries (for PHP, see the DateTime class as mentioned by another commenter).
http://dev.mysql.com/doc/refman/5.5/en/datetime.html
http://php.net/manual/en/class.datetime.php
I just want to expand on the information given here.
This will convert the string into a DateTime object.
$dtObject = new DateTime("2013-11-09T15:14:48.957604");
But, in order to store the timestamp in the database there are several requirements.
Needs to be in Y-m-d H:i:s format.
MYSQL column type must be datetime/timestamp
Needs to be a string.
Now in order to get this timestamp into a MYSQL friendly format we need to use the format function.
$timestamp = $dtObject->format('Y-m-d H:i:s');
You can now INSERT this into the database. You can also output the same way following these date formats.

What's the best way to store date and time in a MySQL database for later display with PHP?

I want to store the date and time that a user performs an action on my website into a MySQL database. I'd like to be able to do the following with ease:
Store the date and time as one field in the database
Use a built in PHP or MySQL function to generate the date-time of the action
Store the date-time based on my server's time, and not worry about user timezones.
Order By the date-time field when I query MySQL
Later, display the date-time in many different formats using built in PHP methods
Here are my questions:
What data type should I use in MySQL ( eg. timestamp, datetime ... )?
What method should I use to generate the date-time ( eg. MySQL's now(), PHP's date() ... )?
What PHP method should I later use to format the date-time in various pretty ways ( eg. 23/4/2012, 5pm on Monday, July 2012 ... )?
I would store it as a datetime, not a timestamp.
I normally use the PHP date function and that way if you ever want to store the time relative to the user's timezone you can simply change the timezone based off the user's settings.
When you pull it out of the database, use strtotime() to convert it, then you can use all the date() features to display it however you want. Example:
echo date('F j, Y',strtotime($db_datetime)); //Displays as 'March 5, 2012'
I've struggled with this question for years, and I'm beginning to think that the best way might be to store the time as an integer that represents Unix time (number of seconds from Jan 1, 1970). I've done this and it works fine.
Personally I've never used datetime, and I can't think of a situation when I ever would use this. It just carries too many problems with it.
Timestamp is a lot better, but in MySQL it can't store a date later than 2032.
I would love to hear some serious discussion on this topic, but Stack Overflow might not be the best place for this.
If you set the mysql data type to a non-nullable timestamp, then save rows with a null value for that column, mysql will automatically update the timestamp for you.
As for reading it back out again, you can just use php's strtotime and the date object to get it into the format you need.
You should use the datetime datatype for your requirement.
It will store both the date and time from your input field based on your query.
For retrieving the datetime you can use the mysql's date_format() function or PHP's date() function.
The datetime will always be stored according to the server's time and not on the clients time.

Any better way to save dates in db than time()?

I am used to save dates in db as INT(11) with a time().
Considering the limitation of time() are there any better way to save that?
I would like to NOT use the database own DATE type (and all the db own date functions).
Thanks
Ok, from the comments, I understand that the problem with using time() is that we're looking to represent dates outside the 01/01/1970 to whenever/2038 range.
In this case, I think it's best to format dates for the DB as YmdHis, stored in a BIGINT (or just Ymd in INT if time isn't needed). You can get use date_create("now")->format($fmt) instead of time(), and where $fmt is either 'Ymd' for date-only or 'YmdHis' for date+time
This gives a latest date somewhere in 922,337,203AD and an earliest in -922,337,203BC with time, or 214,748AD to -214,748BC in an INT with no time.
Use $_SERVER['REQUEST_TIME'].
It's constant for the whole request and it's faster than time() (and UNIX_TIMESTAMP()) because it only requires an array lookup instead of a function call.
It is strange to avoid the standard time managing in DB. Have you ever considered all possible ways of representing if the correctly formated date field?
MySQL::Date and time functions
PostgreSQL::functions datetime
Storing the date in the correct format is more flexible and more efficient in some cases.
Datetimes are more readable for debugging and reading but the same amount of effort as timestamps for date formatting, the NOW keyword in the query makes things clean and tidy too, especially if you don't need the variable apart form the query:
INSERT INTO `mytable` (`id`,`title`,`created`) VALUES (NULL, 'my awesome record', NOW());
You could just use the built in database types for dates and times, or you could just make three integer columns in your table and save the date as integers. Whatever works and is easy to deal with.

How would I do the mysql timestamps in php?

Ok so I have a mysql database and I need an updated_at field and a created_at field like ruby on rails has by default. I was thinking of using a timestamp for the updated field and a datetime for a created at field. I was reading this article to help me choose but i still dont know if there is a standard that is followed that will either do this automatically with automatically or with little extra code...any ideas on this
The best practice would be to use UNIX Timestamps on both.
To have UNIX timestamp in PHP, use the
time();
function, and to have it in MySQL use the
UNIX_TIMESTAMP();
function. PHP can simply convert UNIX timestamps to any formatted date string using
Date();
function. And you can also make calculations with that.
Well the code from php will only provide you with your time as your computer see's it. Where mysql it has the CURRENT_TIMESTAMP.
You could do it entirely in your database management system. For example, MySQL has functions to use the current date or time: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Example: insert into a (CURRENT_TIMESTAMP);
You are on track with using TIMESTAMP for your updated field which provides the functionality you are looking for. To keep your date format consistent, I would then use DATETIME for your created field and use now() on insert.
I prefer UNIX timestamps, but then you have to code for the updated_at field.

Categories