Java论坛小总结,对于学习java的朋友们,日期时间转换都是会遇到的,大家会去网上寻找各式各样的java方法,有的比较的繁琐有的比较的简洁,其实我们也是在追求用最简洁的方式来解决java问题,这样才会体现出我们编程技巧,也会减少java代码行数,不要用那种笨方法来解决这些问题。今天发现了不错的java时间转换的方法,同时可以回去当前日期时间,以及前一年、前一个月日期,与大家分享下吧!java自学
7 \3 \' V8 L" ?7 x, l, i/ m9 ^: e$ J1 I: H) p
1. 获取前一天、前一个月的日期 Calendar calendar = Calendar.getInstance();//此时打印它获取的是系统当前时间
5 l. y& x* x. P1 E& V calendar.add(Calendar.DATE, -1); //得到前一天 String yestedayDate = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()); 3 O6 l7 y V/ s+ a2 `7 [- d
calendar.add(Calendar.MONTH, -1); //得到前一个月" \5 \- {& ]8 r! D% Y1 S) Q
int year = calendar.get(Calendar.YEAR); 6 Z) g9 t* I* V3 x) O3 t( U% R5 N
int month = calendar.get(Calendar.MONTH)+1; //输出前一月的时候要记得加1 1 H9 V' w! y$ K1 N* c8 k
2. 获取当期日期、年份、月份 import java.util.Calendar;
- G* A+ [7 n4 o4 c; S" Dpublic class Main { ^7 I: q, P0 o4 G8 L
public static void main(String[] args) {" \) U1 m1 E" E3 o6 N0 `. o8 Q
Calendar now = Calendar.getInstance();6 ^3 c6 d% ]& i2 t
System.out.println("Current Year is : " + now.get(Calendar.YEAR));
, `6 {0 Z" \9 ~' U // month start from 0 to 111 v- b! @* w \
System.out.println("Current Month is : " + (now.get(Calendar.MONTH) + 1));) B* d5 E* W6 Q5 ~7 B: b
System.out.println("Current Date is : " + now.get(Calendar.DATE));
+ z! ?; g! R! f- T; K+ X2 S }
. K' K, D' |+ E}
* H2 l. l5 S" R* ] {, L8 C
3. 字符串转为日期格式 String date = "2010-02-01 23:59:59"; SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); try { Date d = sf.parse(date); System.out.println(sf.format(d)); } catch (ParseException e) { e.printStackTrace(); }
/ P5 l( I! g$ Q# P/ l0 y* Q |