基础点:日期时间格式的转换

本文详细介绍了在Java中如何使用SimpleDateFormat进行日期时间格式转换,包括从long类型到指定格式的日期转换,以及在SQL中将date类型转换为String类型的日期格式。通过实例展示了不同格式的日期输出。

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

醉过才知酒浓,爱过才知情重,来过才知错与过,你不能做我的诗,正如我不能做你的梦!
public class timeFormatConversion {
public static void main(String[] args) {
//1:系统当前时间, 返回类型是long
long currentTime = System.currentTimeMillis();
System.out.println(“currentTime:”+currentTime);
//date类型
Date nowDate = new Date();
System.out.println(“date1:”+nowDate);
//格式可以自己随意定义的字符串
SimpleDateFormat sdf1 = new SimpleDateFormat(“yyyyMMdd”);
SimpleDateFormat sdf2 = new SimpleDateFormat(“hh:mm”);
SimpleDateFormat sdf3= new SimpleDateFormat(“yyyy-MM-dd hh:mm”);

    String date = sdf1.format(currentTime);
    System.out.println("date:"+date);
    String time = sdf2.format(currentTime);
    System.out.println("time:"+time);
    String s = sdf3.format(currentTime);
    System.out.println("s:"+s);
    String nowDatef = sdf3.format(nowDate);
    System.out.println("nowDatef:"+nowDatef);
}

}
输出的结果是:
currentTime:1547263811242
date1:Sat Jan 12 11:30:11 CST 2019
date:20190112
time:11:30
s:2019-01-12 11:30
nowDatef:2019-01-12 11:30
结论:
这是在Java中将日期转换的方法:无论从数据里哪些什么的类型的数据,都可以通过SimpleDateFormat自定义前端想要的格式,当然也可以在数据库中直接转换好返给前端,但是会稍微影响一下sql的性能。
下面是在sql中将date转换成String 类型的日期格式
select DATE_FORMAT(time ,’%Y-%m-%d %H:%i:%S’)
from table
where mobile=#{mobile}
格式可以自定义:
‘%Y%m%d%H%i%s’
‘%Y-%m-%d %H:%i:%S’
自己总结所用,如有错误之处,请各路大神指正在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值