Java基础/时间日期格式
Java时间日期格式转换
一、Date转String和String转Date
参考博客:https://www.cnblogs.com/sharpest/p/7879377.html
public static void main(String[] args) { String dateStr="2018-2-2 18:00:00"; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date=null; try { date=formatter.parse(dateStr); //字符串转化日期格式=》2018-2-2 18:00:00 System.out.println("字符串转化日期格式=》"+dateStr); } catch (ParseException e) { System.out.println("字符串转化日期格式异常=》"+dateStr); } SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String strDate=format.format(date); //日期转成字符串格式=》2018/02/02 18:00:00 System.out.println("日期转成字符串格式=》"+strDate); }
Calendar日期
一、获取当前日期、当月第1天、当月最后1天
public static void main(String args[]) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Calendar c = Calendar.getInstance(); //【1】获取当天 String curday = format.format(c.getTime()); System.out.println("===============curDay:" + curday);//2017-12-15 //【2】获取当前月第一天: c.add(Calendar.MONTH, 0); //设置为1号,当前日期既为本月第一天 c.set(Calendar.DAY_OF_MONTH, 1); String first = format.format(c.getTime()); System.out.println("===============first:" + first);//first:2017-12-01 //【3】获取当前月最后一天 c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH)); String last = format.format(c.getTime()); System.out.println("===============last:" + last);//last:2017-12-31 //【4】计算当前日期和第1天的时间差 Long diff=Long.parseLong(curday.replace("-",""))-Long.parseLong(first.replace("-",""))+1; System.out.println("diff:"+diff);//15 }
体胖还需勤跑步,人丑就该多读书!