1,时间的格式化
JAVA时间格式化处理(因为C# 的我比较熟悉,所以就。。)
System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
2,时间 与字符串的转化
字符串转 时间:
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
java.util.Date time=null;
try {
time= sdf.parse(sdf.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
时间 转 字符串:
String time="2010-11-20 11:10:10";
Date date = null;
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date=formatter.parse(time);
5.将20101125102503转换成2010-11-25 10:25:03输出
String time="20101125102503";
SimpleDateFormat formatter1=new SimpleDateFormat("yyyy-HH-dd HH:mm:ss");
SimpleDateFormat formatter2=new SimpleDateFormat("yyyyHHddHHmmss");
time=formatter1.format(formatter2.parse(time));
3,时间的加减
C#:
DateTime t1 = DateTime.Parse("2007-01-01");
DateTime t2 = DateTime.Parse("2006-01-01");
System.TimeSpan t3 = t1 - t2; //两个时间相减 。默认得到的是 两个时间之间的天数 得到:365.00:00:00
double getDay = t3.TotalDays; //将这个天数转换成天数, 返回值是double类型的(其实不必转换,因为t3默认就是天数) 得到:
double getHours = t3.TotalHours; //将这个天数转换成小时, 返回值是double类型的
double getMinute = t3.TotalMinutes; //将这个天数转换成分钟, 返回值是double类型的
double getSeconds = t3.TotalSeconds; //将这个天数转换成秒数, 返回值是double类型的
double getMillisecond = t3.TotalMilliseconds; 将这个天数转换成毫秒, 返回值是double类型的
Calendar calendar=Calendar.getInstance();
calendar.setTime(new Date());
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//今天的日期
calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);//让日期加1
System.out.println(calendar.get(Calendar.DATE));//加1之后的日期Top
Date d=new Date();
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
System.out.println("今天的日期:"+df.format(d));
System.out.println("两天前的日期:" + df.format(new Date(d.getTime() - 2 * 24 * 60 * 60 * 1000)));
System.out.println("三天后的日期:" + df.format(new Date(d.getTime() + 3 * 24 * 60 * 60 * 1000)));
GregorianCalendar gc=new GregorianCalendar();
gc.setTime(new Date);
gc.add(field,value);
value为正则往后,为负则往前
field取1加1年,取2加半年,取3加一季度,取4加一周
取5加一天....
java中对日期的加减操作
gc.add(1,-1)表示年份减一.
gc.add(2,-1)表示月份减一.
gc.add(3.-1)表示周减一.
gc.add(5,-1)表示天减一.
以此类推应该可以精确的毫秒吧.没有再试.大家可以试试.
GregorianCalendar类的add(int field,int amount)方法表示年月日加减.
field参数表示年,月.日等.
amount参数表示要加减的数量.