【Java】Date类型获取年月日时分秒的两种方法(12小时制、24小时制)

版权声明:本文为博主原创文章,允许转载,但希望标注转载来源。 https://blog.csdn.net/qq_38410730/article/details/87448312

Java的Date类型是,提供用来描述日期时间的类,它可以存储时间的年月日、时分秒的信息。但是如何从Date的实例中获取这些信息呢?

以前Date提供了一系列的get方法来获取,但是这些方法现在都被弃用了

既然这些方法不能使用了,那我们还能怎样获得呢?

方法一:Calendar类

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());					//放入Date类型数据

calendar.get(Calendar.YEAR);					//获取年份
calendar.get(Calendar.MONTH);					//获取月份
calendar.get(Calendar.DATE);					//获取日

calendar.get(Calendar.HOUR);					//时(12小时制)
calendar.get(Calendar.HOUR_OF_DAY);				//时(24小时制)
calendar.get(Calendar.MINUTE);					//分
calendar.get(Calendar.SECOND);					//秒

calendar.get(Calendar.DAY_OF_WEEK);				//一周的第几天

方法二:SimpleDateFormat类

String[] strNow1 = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString().split("-");

Integer.parseInt(strNow1[0]);			//获取年
Integer.parseInt(strNow1[1]);			//获取月
Integer.parseInt(strNow1[2]);			//获取日

String[] strNow2 = new SimpleDateFormat("hh:mm:ss").format(new Date()).toString().split(":");

Integer.parseInt(strNow2[0]);			//获取时(12小时制)
Integer.parseInt(strNow2[1]);			//获取分
Integer.parseInt(strNow2[2]);			//获取秒

String[] strNow3 = new SimpleDateFormat("HH:mm:ss").format(new Date()).toString().split(":");
		
Integer.parseInt(strNow3[0]);			//获取时(24小时制)
Integer.parseInt(strNow3[1]);			//获取分
Integer.parseInt(strNow3[2]);			//获取秒

猜你喜欢

转载自blog.csdn.net/qq_38410730/article/details/87448312