I am querying an API and I got a date like this: "2019-04-17T14:04:24.224-04:00". I suppose this is an iso date. How can I store the year, month and day on a mysql database? I want the following format "dd/mm/yyyy".
Formats are a display concern, that is it's a function of who is looking at the data, so you don't do it until you know who's looking at it. At the point of display you apply the format required by the user's locale, and quite often adjust for their local time-zone as well.
MySQL's DATE column type is expressed in ISO-8601 format like you have, so you should be able to insert that minus everything after the "T".
So either strip that out before insertion and it should be fine.
On display you can use any of the PHP date formatting functions to get the exact format you want. This is often locale specific.
You'll want to be sure that the time expressed is in the correct time-zone. Do any conversion necessary to get it in the right zone before converting to a date or you may find you're getting the wrong date for several hours of the day.
Generally you should:
Store dates as ISO-8601 formatted values in MySQL's native DATE or DATETIME fields and convert to/from localized formats as dictated by user preferences.
Store any time values as UTC and convert to/from local time as dictated by user preferences.
date("d-m-Y", strtotime("2019-04-17T14:04:24.224-04:00"));
Just do this,
Try this!
update TABLENAME
set date_columnname = LEFT(date_present_columnname,10)
Related
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.
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.
In my php application I have this code:
<?php echo date("d/m/ Y ",strtotime($row["m_date"]));?>
In it, $row["m_date"] is fetching from a database.
The problem is that all the dates are printing perfectly except 27/2/2011. It's printing 1/1/1970 instead.
The date in the database is fine, and prints correctly in a PDF.
I'll assume you're getting the date from the database as the string 27/2/2011 because that's most probably what happens (correct me if I'm wrong).
PHP considers the string 27/2/2011 as being in the m/d/Y format, not d/m/Y and tries to parse under that assumption. Because the date is not valid under that format strtotime returns false. Giving false as the timestamp parameter to date is taken as 0, which is the timestamp for January 1st 1970.
What you need to do is either get your date in another format (or better still, as a timestamp) from the database, or parse it yourself (say using explode).
Good luck,
Alin
The database should be able to return the date to you as a UNIX timestamp. For example, MySQL has the UNIX_TIMESTAMP() function.
SELECT UNIX_TIMESTAMP(date_column) FROM table;
Postgres has date_part
SELECT DATE_PART('epoch', date_column) FROM table;
Most other databases should have similar features. If you can get the date out as a UNIX time stamp you can pass that directly to date() without having to use strtotime() as well.
All of this does of course assume you're using a temporal datatype for the columns in question (timestamp, datetime, timestamp with time zone, etc) and not just storing a string. You are using a temporal type, right? If not, then why not?
if you are storing the date in the database as a timestamp this should work
<?php echo date("d/m/Y",$row["m_date"]);?>
if you are storing the date in the database as a date or datetime this should work
<?php echo date("d/m/Y",strtotime($row["m_date"]));?>
How is the m_date stored in the databases? Is it a datetime object? Or a string.
Problem with strtotime is that it isn't real good at deciphering written dates. So something like 27/2/2011 gives problems while 27/02/2011 gives no problems at all.
So there are 2 solutions:
Make sure all the dates that get entered into the database are of the correct format (dd/mm/yyyy).
Write a regular expression that adds a leading zero to all single characters.
i would like to store the date and time in the following format in the database
a) DD-MM-YYYY or i could add up HH-MM
b) as my servers are located in US i would like to fetch the time as per IST. now that will be GMT : +5:30
earlier i used to store the date in mysql in this format timestamp(int(11)):1291746600. i used to convert the date with strtotime();
currently my intention of storing the date is just to store and display. in the future i would like to calculate the no. of days, months etc.
which would be the best possible solution for this?
P:S : i would appreciate if someone could explain me which datatype to use and how to use it with PHP.
Use DATETIME fields! They are the best format to store dates in mySQL. They offer proper indexing and optimization, and you can use the full range of mySQL's date functions.
Any specific format you need to output the fields in, you can create from a DATETIME field using DATE_FORMAT().
MySQL doesn't support time zones in DATETIME fields - you will usually set a global time zone on the server and use that.
There's good related reading on Timezones in these questions:
MySQL: keep server timezone or user timezone?
Lost in dates and timezones
Use a datetime field.
http://dev.mysql.com/doc/refman/5.1/en/datetime.html
You will have access to a lot of function for date manipulation.
If you want still to use a varchar use the ISO-TIME format (YYYY-MM-DD) not the us.
I think you should use DATETIME data type.
For more operations on date and time have a look at functions listed here
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
I have found a proper solution to my "problem" but even after reading mysql pages, I don't understand the logic behind it.
I currently store registration information in my system in a "datetime" formatted field in one of my tables (YYYY-MM-DD hh:mm:ss).
When I want to display the data on one of my php pages, simply posting the exact field data shows the format mentioned above.
I would THINK simply using date("Y-m-d",$row["DATE"]) where $row["DATE"] corresponds to the particular row value would return the desired format.
Instead I have to use:date("Y-m-d", strtotime($row["DATE"])).
Why is this? My $row["DATE"] field is not a string in the first place. Should I be able to simple rearrange the data stored in a datetime field? Wasn't that the purpose of rebuilding my entire tableset to accomodate datetime?
MySQL has a built in function called date_format which you can use to display the date how you want to.
SELECT DATE_FORMAT(date_field, '%Y-%m-%d') as date_field FROM table_name
The manual has the list of formats and the variables needed to display it that way. Using this method there will be no need to have PHP convert it etc. Plus it is less code on PHP side for something MySQL can handle easily.
EDIT
Sorry, just read you were looking for an explanation.
PHP's date function takes in a UNIX timestamp, which MySQL is not using. MySQL uses a real date format IE: YYYY-MM-DD HH:MM:SS, as you know, this is to be compliant for years later. The UNIX timestamp has a limited range from something like 1969 to 2037 that it is valid for, which makes it really useful for "timestamping" of items such as a chat box message or items they are not expected to be around post those dates, where as the MySQL DATETIME should not die out until the year changes to 5 digits or the world ends.
Read the WIKI on UNIX timestamp for more information on it.
MySQL does allow you to select dates in unix timestamp format, which allows them to be used more easily in PHP, exactly as you requested.
The previous answer seemed to ignore this point, or downplay it due to the range restriction on the unix timestamp, but if it's what you're looking for...
SELECT UNIX_TIMESTAMP(datefield) as u_datefield FROM table
will give you the date in timestamp format, which you can use as you suggested in PHP:
<?php
$showdate = date("Y-m-d",$row['u_datefield']);
?>
As the previous answer suggests, unix timestamps do have a limited range, so if you need dates prior to 1970 or after 2038 it may not be suitable, but for everyday use today it's great.
The main advantage of using timestamps over date strings is that timestamps can be added and subtracted, which is much harder with a date in string format.