java时间的详细案例_用Java实现今天、昨天、前天的日期小例子。

下面是用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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值