7

Is there any way I can get datetime format like 'YYYY-MM-DD HH:MM:SS' to be stored as datetime format in mysql from android date of format 'MM-DD-YY' and time of format 'HH:MM'

Input : android date 'MM-DD-YY' and android time 'HH:MM'
Output: mysql datetime 'YYYY-MM-DD HH:MM:SS'

2 Answers 2

10

Use SimpleDateFormat to parse and format the dates :

// Parse the input date SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm"); Date inputDate = fmt.parse("10-22-2011 01:00"); // Create the MySQL datetime string fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = fmt.format(inputDate); 
Sign up to request clarification or add additional context in comments.

1 Comment

i tried SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = fmt.format("10-22-2011 01:00"); it gives illegal argument exception
1

I find it much easier to store dates as ints in the database e.g. long millis - date.getTime(). Then when you want to display it you can convert it back to a date and add whatever formatting suits your required output.

4 Comments

It's easier, but what if you want to use mysql functions like DAY(), MONTH(), ... ?
That's a very bad idea. In fact it's a question to stack overflow, that usually starts I have this int and I wnat to do something date ish to it in my database...
What's so bad about it? Store it as a string and you've comitted it to a format but as an int you can format it how you want or need.
nice idea John...Specially if you are only going to store and retrieve dates from database,this would be the best option

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.