Java examples for java.util:Month
get Date By Year And Month
//package com.java2s; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Main { public static void main(String[] argv) throws Exception { int year = 2; int month = 2; System.out.println(getDateByYearAndMonth(year, month)); }/*from w w w .j a v a 2s . com*/ private static final String DEFAULT_FORMAT = "yyyy-MM-dd"; public static Date getDateByYearAndMonth(int year, int month) { if (year <= 0 || month <= 0) { return null; } Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.add(Calendar.MONTH, -1); String dateFormat = "yyyy-MM-dd HH:mm:ss"; return formatDate(dateFormat, calendar.getTime()); } private static Date formatDate(String format, Date date) { SimpleDateFormat formater = new SimpleDateFormat(); formater.applyPattern(format); formater.setLenient(false); try { return formater.parse(formater.format(date)); } catch (ParseException e) { return now(); } } public static String format(Date date) { return format(DEFAULT_FORMAT, date); } public static String format(String format, Date date) { if (date == null) { return ""; } SimpleDateFormat formater = new SimpleDateFormat(); formater.applyPattern(format); return formater.format(date); } public static Date now() { return new Date(); } public static Date now(String format) { return formatDate(format, now()); } }