Java之时间转换
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = sdf.parse("2018-06-05 13:01:25"); System.out.println(date.getTime()); System.out.println(sdf.format(date.getTime()));
这个例子就足以说明Date类型的数据如何转换为Long类型
Long类型的日期如何转换为Date
特别是第三方接口,很多接口传参除了传签名外还有时间戳,时间戳通常就是用Long类型的时间表示的(这里指的是将Date转为Long类型)
之所以做主要考虑到安全。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | Date dt = new Date(); System.out.println(dt); //格式: Wed Jul 06 09:28:19 CST 2016 //格式:2018-6-24 String formatDate = null ; formatDate = DateFormat.getDateInstance().format(dt); System.out.println(formatDate); //格式:2018年6月24日 星期三 formatDate = DateFormat.getDateInstance(DateFormat.FULL).format(dt); System.out.println(formatDate); //格式 24小时制:2018-06-24 09:39:58 DateFormat dFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); //HH表示24小时制; formatDate = dFormat.format(dt); System.out.println(formatDate); //格式12小时制:2018-06-24 09:42:44 DateFormat dFormat12 = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" ); //hh表示12小时制; formatDate = dFormat12.format(dt); System.out.println(formatDate); //格式去掉分隔符24小时制:20160706094533 DateFormat dFormat3 = new SimpleDateFormat( "yyyyMMddHHmmss" ); formatDate = dFormat3.format(dt); System.out.println(formatDate); //格式转成long型:1467770970 long lTime = dt.getTime() / 1000 ; System.out.println(lTime); //格式long型转成Date型,再转成String: 1464710394 -> ltime2*1000 -> 2018-06-24 23:59:54 long ltime2 = 1464710394 ; SimpleDateFormat lsdFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); Date lDate = new Date(ltime2* 1000 ); String lStrDate = lsdFormat.format(lDate); System.out.println(lStrDate); //格式String型转成Date型:2018-06-24 10:17:48 -> Wed Jul 06 10:17:48 CST 2016 String strDate = "2018-06-24 10:17:48" ; SimpleDateFormat lsdStrFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); try { Date strD = lsdStrFormat.parse(strDate); System.out.println(strD); } catch (ParseException e) { e.printStackTrace(); } |
以上是比较常用的时间类型转换,通常签名比较常用的就是Long类型的时间戳,支付用的比较多,为了安全起见。
至于String类型的话,什么创建时间,更新时间等比较常用。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述