java 获取本周,本月,本年 的第一天和最后一天
package z_test; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Hello { /** * @param args */ public static void main(String[] args) { //格式化字符串 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar c = Calendar.getInstance(); c.set(Calendar.DAY_OF_WEEK, 2); //本周的第一天,写1获取到的是周日,2获取到的是周一 System.out.println("本周的周一:" + sdf.format(c.getTime())); c = Calendar.getInstance(); c.set(Calendar.DAY_OF_WEEK, 7); //程序里一周的最后一天是周六,不符合中国人习惯,所以+1 c.add(c.DATE, 1); System.out.println("本周的周日:" + sdf.format(c.getTime())); c = Calendar.getInstance(); c.set(Calendar.DAY_OF_MONTH, 1); //获取本月第一天 System.out.println("本月的第一天:" + sdf.format(c.getTime())); c = Calendar.getInstance(); c.add(Calendar.MONTH, 1); //获取本月最后一天 c.set(Calendar.DAY_OF_MONTH, 1); c.add(Calendar.DAY_OF_MONTH, -1); System.out.println("本月的最后一天:" + sdf.format(c.getTime())); c = Calendar.getInstance(); c.set(Calendar.DAY_OF_YEAR, 1); //获取本年第一天 System.out.println("本年的第一天:" + sdf.format(c.getTime())); c = Calendar.getInstance(); c.set(Calendar.DAY_OF_YEAR, 1); //获取本年最后一天 c.set(Calendar.YEAR, 1); c.add(Calendar.DAY_OF_YEAR, -1); System.out.println("本年的最后一天:" + sdf.format(c.getTime())); } }