0

With this query, I get from the database, the month in numeric format. can I get the month in long format? 'MMMM'

private List<String> ottieniMesi(){
    List<String> result1 = new LinkedList<String>();

    SQLiteDatabase db = new DatabaseHelper(getActivity()).getReadableDatabase();

    String sql = "SELECT DISTINCT strftime('%m',"+Table.DATE+") FROM "+Table.TABLE_NAME;
    Cursor c = db.rawQuery(sql, null);

    while (c.moveToNext()){
        result1.add(c.getString(0));

    }
    db.close();
    return result1;
}
user3608814
  • 561
  • 1
  • 8
  • 23

2 Answers2

1

No. sqlite date and time functions do not support such conversion.

Consider doing the conversion in your application code instead.

For example:

int monthNumber = ...; // the value from query
monthNumber--; // convert to 0-based for Calendar
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, monthNumber);
String monthName = c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
laalto
  • 150,114
  • 66
  • 286
  • 303
0

java.time

You can get the name of the month using java.time.Month#getDisplayName.

Demo:

import java.time.Month;
import java.time.format.TextStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // An arbitrary month number for demo - you are getting this value from the DB
        int monthNumber = 0;

        Month month = Month.of(monthNumber + 1);
        String monthName = month.getDisplayName(TextStyle.FULL, Locale.ENGLISH);

        System.out.println(monthName);
    }
}

Output:

January

Note: This code assumes that you are getting 0-based monthNumber i.e. 0 for Jan, 1 for Feb and so on. If it is not the case, use just monthNumber instead of monthNumber + 1.

Learn more about the the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110