获取当前系统时间
获取当前系统时间
Date d = new Date();
System.out.println(d.toString());
输出结果为美式时间格式,用以下办法转换成中式时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String time = sdf.format(d);
System.out.println(time);
获得当前系统时间的第二张办法
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String time = sdf.format(System.currentTimeMillis());
System.out.println(time);
单独获取年月日
单独获取年月日
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(new Date());
System.out.println(gc.get(Calendar.YEAR));
System.out.println(gc.get(Calendar.MONTH) + 1);//月份需要加1
System.out.println(gc.get(Calendar.DAY_OF_MONTH));
设置年月日
gc.set(Calendar.YEAR,2020);
如上,如果再获取年份,那么就成了2020
同样的,如果要让GregorianCalendar的天数加上30天后是几月几号,用
gc.add(30);
日期和字符串互转
日期对象转字符串
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String time = sdf.format(new Date());
字符串转日期对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date d = sdf.parse("2018-05-07 22:22:22");