My database has DATETIME data type, so I need to pass the DATE format to my API parameter. All I found in online is convert date to string type which is not I want
Asked
Active
Viewed 754 times
-1
-
Which API, which API parameter? What does “pass a format” mean (when not a string)? Are you really asking how to store date and time into your database? – Ole V.V. Apr 10 '19 at 05:32
-
You cannot have a format in a `Date` datatype. A format can exist only in a string. See for example [want current date and time in “dd/MM/yyyy HH:mm:ss.SS” format](https://stackoverflow.com/questions/8745297/want-current-date-and-time-in-dd-mm-yyyy-hhmmss-ss-format). – Ole V.V. Apr 15 '19 at 05:09
1 Answers
0
Something like this should work. Your API clearly isn't looking for an actual DATETIME object just a string in the correct format, like so:
public static String getFormattedDateTime(Date date) {
// Get date string for today to get today's jobs
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(date);
}
You can use a method like this if you have a date String rather than a date object. You will parse a string after defining a dateFormat:
public static Date getDateObjectFromDateTime(String dateString) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date inputDate = null;
try {
inputDate = dateFormat.parse(dateString);
} catch(ParseException e) {
e.printStackTrace();
}
return inputDate;
}

brandonx
- 228
- 2
- 13
-
I am actually inserting data from android to WampServer MySQL. If I am passing STRING type to the php script, it is impossible to works – Jin Sheng Apr 09 '19 at 17:34
-
You should handle conversion from string to datetime object within your PHP code, not on the front end. – brandonx Apr 09 '19 at 17:38
-
Also, if you are simply marking the current date and time in your db, use NOW() in your SQL query rather than trying to pass a datetime – brandonx Apr 09 '19 at 17:41
-
Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Apr 10 '19 at 13:37