I want to store dates in mysql so I set the table to be of type 'Date', which is fine but mysql requires that the full date is provided YYYY-MM-DD.
However some of my data does not include day and some is missing the month. Now I could just use a varchar(10) field, but then its difficult to run date based queries on the data.
Is there another date format which is not as strong and would allow me to use ?? or 00 where the day/month is not known?
Following from Babiker's answer, this is what the documentation says:
Ranges for the month and day specifiers begin with zero due to the fact that MySQL allows the storing of incomplete dates such as '2014-00-00'.
You can replace with zeros.
Related
I have a mysql table that has a column with date type.
I'm going to store non-Gregorian date in this column (i.e. Jalali date).
I tested this by using phpMyadmin and storing a Jalali date and no error happend.
Is it a good idea to store non-Gregorian dates in date type?
If not; which is better? storing it as varchar or as timestamp or timestamp as Int or something else?
Is it a good idea to store non-Gregorian dates in date type?
No. Aside that some valid date in one calendar system doesn't exist in another calendar, functions working on DATE typed columns may not work properly. The matter is not just storing data, you need to process this data and for example compare them with CURDATE().
storing it as varchar or as timestamp or timestamp as Int or something else?
If you choose a proper formatting, use two digits for month and day and static number of digits for year, a character string type, CHAR or VARCHAR is fine. Comparing theme against each other is just a lexical comparison and you still can write your functions o procedures to extend functionality.
Choosing TIMESTAMP or DATE changes the question as former represents a specific time but latter represents a specific entry in calendar. If you want put time beside date they still differ in meaning. You should think about issues like daylight-saving time changes which cause some people prefer to put calendar entry (DATE) and some prefer seconds passed from 1 Jan 1970 (TIMESTAMP). e.g. there is two timestamps for 1393-06-30 23:30:00 in Hijri Shamsi calendar based on current Iran government laws.
You can store non-gregorian dates in an integer field in the database.
Examples:
year:1396, month:11, day:17 => 13961117
year:1393, month:4, day:9 => 13930409
by using this, you can query rows to find a specific date and dates that are <=> than a specific date, but unfortunately, you can't compare them against each other.
Internal storage and binary interface of almost all database systems have nothing to do with calendars. you just store date (and possibly time) into database, providing no calendaring information. It's only a simple number of days, seconds or milliseconds past from a specific point in time (usually midnight 1970-01-01).
So you just need to provide an API abstraction of dates in your application layer. Everything else will work. You convert all your dates to Gregorian or Unix timestamp, and send queries to MySQL as usual.
Non Gregorian calendar still operate by Year, Month, Day and Time so it can be stored in 4 separate columns like:
CREATE TABLE `Calendar` (
`Year` int,
`Month` tinyint,
`Day` tinyint,
`Time` time
);
I make possible to store dates without conversion and permit group by Year and Month
I am new in php and I saw some programmer store datetime in database by php date() or mysql NOW() or take column as timestamp. I want to know that the difference between these three is and also how to convert these three formats to users local time worldwide.
As per the mysql's law you can have only one timestamp field,no
restrictions for having number of datetime field..
You can set the
timestamp field for onupdate current timestamp or current
timestamp..And these field type not affecting the date insert
method..
If you are using date() function you can set your own
date format..But not in the now()
For date format the syntax check this article https://www.w3schools.com/php/func_date_date.asp
Finaly Datetime and timestampis mysql
date() and NOW()is php
There's a few things to consider:
TIMESTAMP columns are limited to dates between 1931 and 2038, as they're 32-bit timestamp values.
DATETIME columns can go up to the year 9999. While they don't auto-populate like TIMESTAMP values do by default, they're less restricted, you can have as many as you want per table.
When inserting times your PHP clock and your database clock might differ slightly. Using NTP can help narrow that gap, but drifts do happen. PHP's date() function requires formatting into ISO-8601 format for inserting (YYYY-MM-DD HH:MM:SS). The MySQL NOW() function does not, same with UTC_TIMESTAMP().
I strongly recommend using UTC time in your database for a few reasons:
If you store in local time you'll need to store the time-zone as well, and those can change in wild and bizarre ways.
You may need to accommodate other time zones in the future, which means you might have multiple local times in your data where each record might have a different meaning from others.
Your server might get moved between time-zones which can shift all your data.
So store with UTC and render out as local times based on the user's time-zone preference or some sensible default for your application. Remember, time formatting is often a fussy thing, every country has different date formatting standards, and even a single country might have multiple preferences for long-form, short-form, or numerical forms.
After spending over 6 hours trying to do this and trying many different published solutions I am just going to ask the exact question.
I want to have the user enter the date and time in US format in an html form. Format for today is 12/16/2012 02:53 using 24 hour time format.
Lets call it start_date.
Then I want to insert the record including the start_date into an mysql database into a datetime type field.
I am using PHP 5.2. Many of the solutions I saw required 5.3 and none of the workarounds for 5.2 worked.
Can someone please give me an exact example.
Thank you.
Use regex or string processing to extract fields from your current format.
Create date in MySQL format.
Insert in the database.
See here : date_create_from_format equivalent for PHP 5.2 (or lower)
Actually the format of your date in not valid to be inserted in mysql table the format must be YYYY-mm-dd Hour:min:sec, in order to be place in datetime field. But if you use the field type as varchar you don't need to care about format. you can insert in whatever format you wish.
Or you can rely on MySQL parsing:
SELECT STR_TO_DATE('12/16/2012 02:53', '%m/%d/%Y %H:%i')
Note: this expects two-digit month, day and hour, i.e. 01 - not 1.
See MySQL Date format for other formats.
Also for this approach to be of practical use you will have to process failed parsing attempts: for example, you can make your Datetime column NOT NULL so that all inserts or updates fail if you tried to write NULL into it (STR_TO_DATE will return NULL for invalid date)
You asked for an example, which no one has supplied yet, so here it is:-
$start_date = date("Y-m-d H:i:s", strtotime("12/16/2012 02:53"));
echo $start_date;
Output:-
2012-12-16 02:53:00
This format matches the MySql DateTime type.
See working example here which also demonstrates that it works in PHP 5.2.
See the manual for strtotime and date.
You can use strtotime(). It parses dates according to the format. For instance dates using / (MM/DD/YYYY) are parsed using the American format, and dates using - or . (DD-MM-YYYY or DD.MM.YYYY) are parsed using the European format. See the third note in the documentation.
You really should look at upgrading to 5.4 if at all possible. There you can use the really nice date classes.
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 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.