I would like to save NSDate to a MySQL field. Which type is the best? DATE or TIMESTAMP? And how to format my NSDate to send it (to a PHP script) and save it in my field?
You asked two questions.
Regarding MySQL DATETIME vs TIMESTAMP, see Should I use field 'datetime' or 'timestamp'?
Regarding getting from NSDate to MySQL via PHP...
NSDate is an object representing a point in time. To send it over a network, you need to serialize it into some format (that is, turn it into a string). The easiest thing to do is put it in the format yyyy-MM-dd HH:mm:ss
, because that is what MySQL will want.
Use NSDateFormatter
to convert the NSDate object into a string of that format. Make sure to set the formatter time zone to UTC, so you will get consistent results regardless of the time zone of the device/computer your NSDate was computed on. Then send it over the network to your PHP script.
In the PHP script, you can just take the value directly and save it to a DATETIME column.
Bonus: make sure you use prepared statements (the PHP PDO library, which comes with PHP will allow this), otherwise you will be at risk for SQL injection.