java 中常用的时间操作以及格式转化,thymeleaf,jsp转化

本文深入讲解了Java中处理时间的多种方法,包括获取时间戳、将时间戳转换为Date对象、将Date对象以指定格式输出、将字符串转换为Date对象、Date与Calendar的相互转换,以及如何使用Calendar获取具体的年月日时分秒。同时,文中还提供了在Thymeleaf和JSP中进行时间格式转换的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获取时间戳
//方法 一
System.currentTimeMillis();
//方法 二
Calendar.getInstance().getTimeInMillis();
//方法 三
new Date().getTime();

时间戳转为Date

		Date tt=new Date(System.currentTimeMillis());

把Date实例以指定格式输出(以指定格式输出当前时间)

		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String curDate = s.format(Calendar.getInstance().calendar.getTime());
		//String curDate = s.format(new Date());

把字符串转化为Date

		Date date= s.parse(curDate);

Date转化为Calendar

		Calendar calendar=Calendar.getInstance();
		calendar.setTime(new Date());

Calendar转化为Date

		Calendar calendar=Calendar.getInstance();
		calendar.getTime()

获取时间的 年、月、日、时分秒

 //获取年
 		Calendar calendar=Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        //获取月份,0表示1月份
        int month = calendar.get(Calendar.MONTH) + 1;
        //获取当前天数
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        //获取当前小时
        int time = calendar.get(Calendar.HOUR_OF_DAY);
        //获取当前分钟
        int min = calendar.get(Calendar.MINUTE);
        //获取当前秒
        int sec = calendar.get(Calendar.SECOND);

thymeleaf中时间格式转换

<p th:text="${#dates.format(messageUser.responsetime,'yyyy-MM-dd HH:mm:ss')}"></p>

jsp中时间格式转换

<p><fmt:formatDate value="${messageUser.responsetime}" pattern="yyyy-MM-dd HH:mm:ss"/></p>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值