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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
NSDateFormatterto 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.