Reputation: 25
I'm getting the date from user and storing it as sting in database. For example my date in database looks "22/09/2014". Now I want to get only month(September) from that date. How can I get that?
My Code is
public ArrayList<String> getMonths(){
String SELECT_MON = "select strftime('%m',"
+ Diary_DBHandler.PERSONAL_DATE + ") from " + Diary_DBHandler.TABLE_PERSONAL + ";";
Cursor c = database.rawQuery(SELECT_MON, null);
c.moveToFirst();
ArrayList<String> mon=new ArrayList<String>();
if (c != null)
{
while(!c.isAfterLast()) {
System.out.println(mon);
mon.add(c.getString(0));
c.moveToNext();
}
c.close();
}
return mon;
}
Upvotes: 1
Views: 627
Reputation: 2671
Here is an example to convert a string date to Date format
String dateString = "03/26/2012 11:49:00 AM";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(convertedDate);
And if you only want the month, take a look at the method getMonth();
Date Android Developer
Notice that it's a better way to store the timestamp (long) on DB than a string date.
Upvotes: 0
Reputation: 157437
you can get a Date object with a SimpleDateFormat
. The pattern for your String ("22/09/2014") is dd/MM/yyyy
Date date = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH).parse(string);
From the date you can build a Calendar object
Calendar cal = Calendar.getInstance();
cal.setTime(date);
and from the Calendar you can extract easily the month, with
cal.get(Calendar.MONTH)
Upvotes: 1