下面是用Java实现今天、昨天、前天的日期小例子,大家可以试试,有什么问题我们互相讨论。
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class TestStr {
public static void main(String[] args) {
getDates();
}
public static void getDates() {
int currYear,currMonth,currDate;
Calendar calendar=Calendar.getInstance();
currYear=calendar.get(Calendar.YEAR);
currMonth=calendar.get(Calendar.MONTH)+1;
currDate=calendar.get(Calendar.DATE);
System.out.println("今天:"+currYear+"-"+currMonth+"-"+currDate);
//判断昨天是不是上一年。
if (currMonth==1&&currDate==1) {//是一月一号
System.out.println("--------1111---------");
System.out.println("昨天是:"+(currYear-1)+"-"+12+"-"+31);
System.out.println("前天是:"+(currYear-1)+"-"+12+"-"+(31-1));
}
else if (currMonth==1&&currDate==2) {//是一月一号
System.out.println("--------222---------");
System.out.println("昨天是:"+(currYear)+"-"+currMonth+"-"+(currDate-1));
System.out.println("前天是:"+(currYear-1)+"-"+12+"-"+31);
}
else if (currMonth>1&&currDate>2) {
System.out.println("--------333---------");
System.out.println("昨天是:"+(currYear)+"-"+currMonth+"-"+(currDate-1));
System.out.println("前天是:"+(currYear-1)+"-"+currMonth+"-"+(currDate-2));
}
else if (currMonth>1&&currDate==2) {
System.out.println("--------4444---------");
System.out.println("昨天是:"+(currYear)+"-"+currMonth+"-"+(currDate-1));
System.out.println("前天是:"+(currYear-1)+"-"+(currMonth-1)+"-"+(getLastDayOfUpMonth(currYear,currMonth,currDate)));
}
else if (currMonth>1&&currDate==1) {
System.out.println("--------5555---------");
System.out.println("昨天是:"+(currYear)+"-"+(currMonth-1)+"-"+(getLastDayOfUpMonth(currYear,currMonth,currDate)));
System.out.println("前天是:"+(currYear-1)+"-"+(currMonth-1)+"-"+(getLastDayOfUpMonth(currYear,currMonth,currDate)-1));
}
}
public static int getLastDayOfUpMonth(int year,int month,int date) {
Calendar calendar = new GregorianCalendar(year,month,date);
calendar.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
calendar.add(Calendar.MONTH,-1);//月增减1天
calendar.add(Calendar.DAY_OF_MONTH,-1);//日期倒数一日,既得到本月最后一天
//System.out.println("上个月的最后一天是:"+calendar.get(Calendar.DATE)+"号");
return calendar.get(Calendar.DATE);
}
}
Calendar calendar=Calendar.getInstance();
calendar.add( Calendar.DAY_OF_MONTH, -2 ); 减去两天
SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd"); //格式化当前系统日期
String dateTime = dateFm.format(calendar.getTime()); 获得减去两天后的年月日
System.out.println(dateTime);