import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;
//当前时间
Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String mDateTime=formatter.format(cal.getTime());
out.println(mDateTime);
out.println("<br>");
//1年前日期
java.util.Date myDate=new java.util.Date();
long myTime=(myDate.getTime()/1000)-60*60*24*365;
myDate.setTime(myTime*1000);
String mDate=formatter.format(myDate);
out.println(mDate);
out.println("<br>");
//明天日期
myDate=new java.util.Date();
myTime=(myDate.getTime()/1000)+60*60*24;
myDate.setTime(myTime*1000);
mDate=formatter.format(myDate);
out.println(mDate);
out.println("<br>");
//两个时间之间的天数
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date date= myFormatter.parse("2003-05-1");
java.util.Date mydate= myFormatter.parse("1899-12-30");
long day=(date.getTime()-mydate.getTime())/(24*60*60*1000);
out.println(day);
out.println("<br>");
//加半小时
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date date1 = format.parse("2002-02-28 23:16:00");
long Time=(date1.getTime()/1000)+60*30;
date1.setTime(Time*1000);
String mydate1=formatter.format(date1);
out.println(mydate1);
out.println("<br>");
//年月周求日期
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM F E");
java.util.Date date2= formatter2.parse("2003-05 5 星期五");
SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd");
String mydate2=formatter3.format(date2);
out.println(mydate2);
out.println("<br>");
//求是星期几
mydate= myFormatter.parse("2001-1-1");
SimpleDateFormat formatter4 = new SimpleDateFormat("E");
String mydate3=formatter4.format(mydate);
out.println(mydate3);
out.println("<br>");
//日期加减某些天、月、年
Calendar cal = Calendar.getInstance();//Get today´s date
cal.add(Calendar.DAY_OF_MONTH,20);
System.out.println("20 days later:"+cal.getTime());
cal.add(Calendar.DAY_OF_MONTH,-20);//Return back
cal.add(Calendar.MONTH,2);
System.out.println("2 month later:"+cal.getTime());
cal.add(Calendar.MONTH,-2);
cal.add(Calendar.YEAR,2);
System.out.println("2 years later:"+cal.getTime());
JAVA中的日期时间操作
最新推荐文章于 2023-04-29 18:53:55 发布