0

I am trying to get tweet information from twitter in json format. And store them into a database, but the problem is twitter's date format. I get date as string

String time = ((JSONObject)array.get(i)).get("created_at").toString();

It prints

 Mon Aug 10 07:34:06 +0000 2015 

for example. But of course i cannot store that in this format into database, how can i convert that to Mysql date time in java ? Any help is appreciated

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Toolbox
  • 21
  • 8
  • what is ur expected format ( **Mysql date time format** )? – Bacteria Aug 20 '15 at 08:15
  • What *exactly* is returned by call to `get( "created_at" )`? – Basil Bourque Aug 20 '15 at 08:23
  • @Pitchers yyyy-MM-dd HH:mm:ss – Toolbox Aug 20 '15 at 09:20
  • @BasilBourque it returns me this date > Mon Aug 10 07:34:06 +0000 2015 – Toolbox Aug 20 '15 at 09:20
  • @BasilBourque and i need to convert that to 2015-08-10 07:34:06 – Toolbox Aug 20 '15 at 09:26
  • @Toolbox I doubt the call to get is returning a String because why would you call `toString` on a String? So I'll ask again, ***exactly*** what class is the object returned by the call to `get("created_at")`? I ask because that is the key to a better solution. – Basil Bourque Aug 20 '15 at 14:27
  • @BasilBourque thanks a lot for paying attention to my question, I found a solution, if you are interested to see, i posted it as answer with code betics. there you can see the answer of your question too. – Toolbox Aug 21 '15 at 11:48
  • @Toolbox I asked what object type you were getting because I suspect you already had a date object in hand, so you didn't need to call toString, do you didn't need to parse. **Parsing a string of a date to get a date** is a silly waste of time if you could simply have used the original date in the first place. – Basil Bourque Aug 21 '15 at 16:21

3 Answers3

2

Get the string:

String time = "Mon Aug 10 07:34:06 +0000 2015";

Create a DateFormat to parse this String

DateFormat df = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");

And parse the string (ParseException may be thrown)

DateTime date = df.parse(time);

UPDATE: in order to store in MySql format DateTime, I use Java Timestamp.

// get the date
Date date = (Date)((JSONObject)array.get(i)).get("created_at");
// convert to timestamp
Timestamp ts = new Timestamp(date.getTime());

After you can send it to your database to persist.

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
0

You could use DateFormat.parse(String s)

Java Doc

MickMRCX
  • 153
  • 12
0

thanks guys, i solved my problem like that ;

String time = ((JSONObject)array.get(i)).get("created_at").toString();
java.util.Date date = new Date(time);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);
Toolbox
  • 21
  • 8