Java tutorial
//package com.java2s; import java.util.Calendar; import java.util.Date; public class Main { /** * @param period : today, this_week, this_month, this_year, none * @return a date filter string for making query. e.g. date >= 2013-1-1 for this_year * return null if period is none. */ @SuppressWarnings("deprecation") public static String getDateFilterString(String period) { if (period == null) return null; Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; // 1 - 12 int date = calendar.get(Calendar.DATE); // 1 - 31 String dateFilterString = null; if (period.equalsIgnoreCase("today")) { dateFilterString = "date >= " + year + "-" + month + "-" + date; } else if (period.contains("week")) { int offset = calendar.get(Calendar.DAY_OF_WEEK) - calendar.getFirstDayOfWeek(); long timeInMillis = calendar.getTimeInMillis() - offset * 24 * 60 * 60 * 1000; Date firstDay = new Date(timeInMillis); dateFilterString = "date >= " + (firstDay.getYear() + 1900) + "-" + firstDay.getMonth() + "-" + firstDay.getDate(); } else if (period.contains("month")) { dateFilterString = "date >= " + year + "-" + month + "-1"; } else if (period.contains("year")) { dateFilterString = "date >= " + year + "-1-1"; } return dateFilterString; } public static int getMonth(String str) { if (str.equals("jan")) return Calendar.JANUARY; if (str.equals("feb")) return Calendar.FEBRUARY; if (str.equals("mar")) return Calendar.MARCH; if (str.equals("apr")) return Calendar.APRIL; if (str.equals("may")) return Calendar.MAY; if (str.equals("jun")) return Calendar.JUNE; if (str.equals("jul")) return Calendar.JULY; if (str.equals("aug")) return Calendar.AUGUST; if (str.equals("sep")) return Calendar.SEPTEMBER; if (str.equals("oct")) return Calendar.OCTOBER; if (str.equals("nov")) return Calendar.NOVEMBER; if (str.equals("dec")) return Calendar.DECEMBER; return -1; } }