java 常用日期处理

java获得系统当前时间的几种方法 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(System.currentTimeMillis());//获得时间1毫秒数 Date date = new Date();//获得时间2 System.out.println(date);//Tue Jun 14 22:16:23 CST 2011 System.out.println(date.getTime());//毫秒数 System.out.println(sdf.format(date));//2011-06-14 22:16:23格式化日期 Calendar c = Calendar.getInstance();//获得时间3 System.out.println(c.getTime());//Tue Jun 14 22:16:23 CST 2011 //Calendar向Date转化 date = c.getTime(); //Date向Calendar转化 c.setTime(date); /** * 判断时间是否符合yyyy-MM-dd格式 * @param s * @return */ public static boolean checkDate(String s){ boolean ret = true; try{ DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); ret = df.format(df.parse(s)).equals(s); } catch(ParseException e){ ret = false; } return ret; } /** * 返回日期对应的节日 * @param s * @return */ public Object dateinfo(String s){ String a[]=s.split("-",2);//将时间分成两部分 Hashtable fest =new Hashtable(); fest.put("01-01","元旦节"); fest.put("02-14","情人节"); fest.put("03-12","植树节"); fest.put("03-15","消费者节"); fest.put("04-01","愚人节"); fest.put("04-05","清明节"); fest.put("05-01","劳动节"); fest.put("06-01","儿童节"); fest.put("07-01","建党节"); fest.put("08-01","建军节"); fest.put("09-10","教师节"); fest.put("10-01","国庆节"); fest.put("12-25","圣诞节"); if(fest.containsKey(a[1])){ return fest.get(a[1]); } else{ return "无节日"; } } /** * 根据日期返回星座类型 * @param s * @return */ public String xingzuo(Date s){ Calendar cal = Calendar.getInstance(); cal.setTime(s); String xingzuo="无"; int day=cal.get(Calendar.DAY_OF_YEAR); if((cal.get(Calendar.YEAR)%4==0)&&(cal.get(Calendar.YEAR)%100!=0)||(cal.get(Calendar.YEAR)%400==0)){ if((day>=1 &&day<=19)||(day>=357&&day<=366)){ xingzuo= "魔蝎座"; } else if(day>=20 &&day<=49){ xingzuo= "水瓶座"; } else if(day>=50 &&day<=80){ xingzuo= "双鱼座"; } else if(day>=81 &&day<=110){ xingzuo= "白羊座"; } else if(day>=111 &&day<=141){ xingzuo= "金牛座"; } else if(day>=142 &&day<=173){ xingzuo= "双子座"; } else if(day>=174 &&day<=203){ xingzuo= "巨蟹座"; } else if(day>=204 &&day<=235){ xingzuo= "狮子座"; } else if(day>=236 &&day<=266){ xingzuo= "处女座"; } else if(day>=267 &&day<=296){ xingzuo= "天秤座"; } else if(day>=297 &&day<=326){ xingzuo= "天蝎座"; } else if(day>=327 &&day<=356){ xingzuo= "射手座"; } } else{ if((day>=1 &&day<=19)||(day>=357&&day<=366)){ xingzuo= "魔蝎座"; } else if(day>=20 &&day<=48){ xingzuo= "水瓶座"; } else if(day>=49 &&day<=79){ xingzuo= "双鱼座"; } else if(day>=80 &&day<=109){ xingzuo= "白羊座"; } else if(day>=110 &&day<=140){ xingzuo= "金牛座"; } else if(day>=141 &&day<=172){ xingzuo= "双子座"; } else if(day>=173 &&day<=202){ xingzuo= "巨蟹座"; } else if(day>=203 &&day<=234){ xingzuo= "狮子座"; } else if(day>=235 &&day<=265){ xingzuo= "处女座"; } else if(day>=266 &&day<=295){ xingzuo= "天秤座"; } else if(day>=296 &&day<=325){ xingzuo= "天蝎座"; } else if(day>=326 &&day<=355){ xingzuo= "射手座"; } } return xingzuo; }

将字符串转化为日期类型

String s = "1970-12-30 08:24:37.0"

Timestamp ttime = new Timestamp.valueOf(s);

你可能感兴趣的:(java 常用日期处理)