I have a DB table with relation 1: N where N represents multiple dates for one event. The column with the dates is DateTime type, and I would like to keep the Time option for later use, but it won't be so bad if I have to change it to Date type.
The problem comes when I have to show those multiple dates in some GUI. I get the dates with the GROUP_CONCAT function which means that in JavaScript I operate with a string with comma-separated values representing the different dates, which by now is in the default SQL DateTime format - YYYY-mm-dd hh:mm:ss.
I use the split(',') function to get each date-time value and what I can do is to change the type of the SQL column to Date so when I split the string in JavaScript to end up with YYYY-mm-dd values. Which should be reversed to dd-mm-YYYY for the GUI.
I'm not sure how to proceed here. I have in mind two main options:
First: Maybe there's a way to use dd-mm-YYYY format in SQL which will solve all the problems.
Second: some kind of (complex?!?) String manipulation in JavaScript to split the string of dates into an array with multiple elements and then try to format each element the way I need.
Honestly - I want to avoid the second option, but don't know if the first is possible, and maybe, there's another way that I haven't think of.
Try this..
SELECT GROUP_CONCAT(DATE_FORMAT( date_time_column, '%d-%m-%Y' )) FROM test_table;
First of all I advise to use the native Date/DateTime-format everywhere in your code and only use localized variations like dd-mm-yyyy only where you really want to display it. First reason: it is consistent in your code. Second reason: Sorting.
Example:
2012-03-01 > 01-03-2012
2012-05-12 > 12-05-2012
2012-01-03 > 03-01-2012
Sorted by the native format you'll get...
1: 2012-01-03
2: 2012-03-01
3: 2012-05-12
Sorted by the output format dd-mm-yyyy it will look like this...
1: 01-03-2012
2: 03-01-2012
3: 12-05-2012
...and I doubt this is what most people want.
Adjusting the output via SQL
You can change the output in your SELECT-query , most RDBMS offer functions for this. For example, in MySQL it is DATE_FORMAT, which looks like this:
SELECT DATE_FORMAT(NOW(), '%d-%m-%Y');
Adjusting the output via SQL
You can also change the output using php, which is explained here.
Adjusting the output via JavaScript
It isn't hard to do this in JavaScript, too: Here is a great SO post which explains it in detail.
Related
I've been asked to migrate data from one table to another. The old data includes a series of dates entered in a mishmash of whatever format the user felt like using at the time, the new format requires separate FROM date and TO date fields in MM/YYYY.
So some dates are a single date, such as DD.MM.YYYY or DD/MM/YY or DD YYYY or YYYY or again whatever. Some dates are both dates, such as DD.MM.YYYY-DD/YYYY or DD/MM/YY--DD/MM/YYYY. So just a mess. There are only a couple hundred rows but I don't feel like going through and changing them manually if I can avoid it.
Most of the Google results are for converting one format to another format, how can I convert from a mess of formats to one?
Using a single expression to encompass all combinations is hard so just do the patterns one by one:
UPDATE olddata,newdata
SET newdata.date=STR_TO_DATE(olddate.date, "%d.%m.%Y")
WHERE olddata.id=newdata.id
AND olddata.date REGEXP '[:digit:]{1,2}\.[:digit:]{1,2}.[:digit:]{4}'
AND newdata.date IS NULL
Do this a multiple times for each date format, and use the right expression in STR_TO_DATE. Experiment selecting with the right regulate expression before doing the update.
Eventually you'll have enough record to edit manually
I have a case to query the table using WHERE clause in which I just want to use a 'piece of string' from the field to compare to my string as a condition for selecting.
In the picture, I just want to use month and year from date field to compare with $indicator = 03/2013.
Any idea how can performing the query, so the result would look like:
Any help will appreciated. Thank you in advanced.
Most likely, you aren't dealing with strings in the table, as it's most likely dates. If you are dealing with strings, it's
SELECT * FROM table WHERE DATE LIKE '%03/2013';
where % is a wildcard like * in the old dos days
For actual date fields, (which you would be better off using), it's a simple between
SELECT * FROM table WHERE DATE BETWEEN '01/03/2013' AND '31/03/2013'
Note that you need to follow proper date formatting for your engine, for something like MySQL you'd be better off using '2013-03-01' and '2013-03-31'
The hardest part will be coming up with the first and last day, but for that, I'd look at strtotime(), which allows you to put in things like 'Last day of the month' and such. You'd have to format it correctly, and play with the strings, but it's rather trivial with what strtotime() can do.
USE LIKE in your mysql query instead of =
Reference : (source)
It seems like there are too many complicated ways of doing this, so I'm looking for a clean, succinct answer to this issue.
I write a blog, I click submit, and the title, content, and timestamp INSERTS INTO my blog table. Later, the blog is displayed on the blogindex.php page with the date formatted as MM-DD-YYYY.
So this is my 3 step question:
What is the best column type to insert the date into? (ex: INT, VARCHAR, etc)
What is the best INSERT INTO command to use? (ex: NOW(), CURDATE(), etc)
When I query the table and retrieve this data in an array, what is the best way to echo it?
I'm new at PHP/MySQL, so forgive me if I don't know the lingo and am too frustrated reading 1000 differing opinions of this topic that do not address my issue specifically, or only cover one of the 3 questions...
Here is my opinion on your three questions:
Use the correct data type: Date or DateTime. I would choose for the DateTime type as you store the time as well (might be very handy if you want to have some kind of order, when you added the posts).
It all depends whether you just want the Date (use CURDATE()) or the Date + Time (use NOW()).
You fetch the data and format it how you want it. Don't format it yet in the query, just use the correct PHP functions for it (for example with DateTime). How you fetch the data, doesn't matter too much; you can use PDO or MySQLi or ...
Always store and process dates and times in UTC and perform timezone adjustments in your presentation layer - it considerably simplifies things in the long-term.
MySQL provides a number of different types for working with dates and times, but the only one you need to worry about is DATETIME (the DATE type does not store time information, which messes up time zone conversion as information is lost, and the TIMESTAMP type performs automatic UTC conversion (which can mess up programs if the system time zone information is changed) and has a smaller range (1970-2038).
The CURDATE() function returns only the current date and excludes time information, however this returns information in the local timezone, which can change. Avoid this. The NOW() function is an improvement, but again, returns data in the current time zone.
Because you'll want to keep everything in UTC you'll actually want to use the UTC_TIMESTAMP function.
To return the value you'll need to execute SQL commands in sequence with variables, like so:
SET #now = UTC_TIMESTAMP()
INSERT INTO myTable ( utcDateTimeCreatedOrSomething ) VALUES ( #now )
SELECT #now
Date would probably be the best type, although datetime will work as record more accurate as well.
There isn't a 'best insert into', but what do you really want and how accurate you want the date to be. For a blog, I would say make it datetime and use NOW(). so visitors can see quite accurate of when this post is made.
surely you can easily find huge to run sql and fetch a select query from sql using php by google, so I'll leave this easy work to your self.
For echo the date, you can use the php date format such as:
$today = date("m-d-y"); // 03-10-01
I think Styxxy has it pretty well right, but here is a links for your PHP date formatting part...
How to format datetime most easily in PHP?
(Supporting link: http://php.net/manual/en/datetime.format.php )
Basically it's
echo date("d/m/Y", strtotime('2009-12-09 13:32:15'))
... although, I think the strtotime is unnecessary as it should already have the type of datetime.
In terms of the MySQL, yes, do it as a datetime col, use NOW() as the SQL keyword, and depending on how you want to get it from the database you could...
SELECT CAST(col_name AS DATE) .... or .... SELECT CAST(col_name AS DATETIME) <-- this last one is implied due to the col type.
good luck! :)
Is it possible to change the current 24 hr format like 22:16:08 to something like 10:16:08 in mysql?
I want to change how these values are saved. Is it possible or I will just let php handle things for me?
Don't change the way how these values are saved. Change the way they are output.
See TIME_FORMAT()
In your case, this would show a TIME field as 10:16:08 PM:
SELECT TIME_FORMAT(timefield, "%l:%i:%s %p") AS date_formatted;
You should always store date/time values in their native format, which in MySQL is the 24hr format. You can change how they're retrieved with
SELECT DATE_FORMAT(somedatetimefield, 'format string here')
FROM table
where the format string options are defined here
If doing that manually for every query is a problem, you can always create a view to do it for you automatically.
You really shouldn't change how the data is saved in MySQL. Instead you should only present it differently. You can use PHP's date function to format the date in anyway you want. This is a huge advantage because you are separating how the data is saved and how the data is presented.
Using DATEFORMAT you can save/fetch the date how you wish (much like PHP date()'s syntax)
Like Pekka said: Don't change the way how these values are saved.
You can also easily handle this in php using date()
like date("hh:ii:ss")
This puts out the format you used in your example. (which is 12-hours format and leading zeros.)
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.