JAVA中获取系统当前时间

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34781336/article/details/80519800

1.通过Util包中的Date获取

Date date = new Date();
SimpleDateFormat dateFormat= new SimpleDateFormat(“yyyy-MM-dd :hh:mm:ss”);
System.out.println(dateFormat.format(date));

2.通过Util包的Calendar 获取

Calendar calendar= Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat(“yyyy-MM-dd :hh:mm:ss”);
System.out.println(dateFormat.format(calendar.getTime()));

3.通过Util包的Calendar 获取时间,分别获取年月日时分秒

Calendar cal=Calendar.getInstance();
int y=cal.get(Calendar.YEAR);
int m=cal.get(Calendar.MONTH);
int d=cal.get(Calendar.DATE);
int h=cal.get(Calendar.HOUR_OF_DAY);
int mi=cal.get(Calendar.MINUTE);
int s=cal.get(Calendar.SECOND);
System.out.println(“现在时刻是”+y+”年”+m+”月”+d+”日”+h+”时”+mi+”分”+s+”秒”);

java中时间24小时和12小时设置

Calendar
Calendar date = Calendar.getInstance();
date.get(Calendar.HOUR_OF_DAY );//得到24小时机制的
date.get(Calendar.HOUR);// 得到12小时机制的

SimpleDateFormat
SimpleDateFormat format = new SimpleDateFormat(“yyyyMMdd_HH_mm_ss”);//24小时机制
SimpleDateFormat format = new SimpleDateFormat(“yyyyMMdd_hh_mm_ss”);//12小时机制

时间转为字符串类型

java.text.SimpleDateFormat类

字符串转换成日期类型:
方法1:

Date date=new Date(“2008-04-14”);

方法2:

SimpleDateFormat sdf=new SimpleDateFormat(“yyyy-MM-dd”);//小写的mm表示的是分钟
String dstr=”2008-4-24”;
java.util.Date date=sdf.parse(dstr);

日期转换成字符串:

SimpleDateFormat sdf=new SimpleDateFormat(“yyyy-MM-dd”);
java.util.Date date=new java.util.Date();
String str=sdf.format(date);

猜你喜欢

转载自blog.csdn.net/qq_34781336/article/details/80519800