Java中获取当前时间并格式化

 主要有两种方式,其中使用Date比较好控制,代码如下:

复制代码
//使用Calendar
Calendar now = Calendar.getInstance();
System.out.println("年:" + now.get(Calendar.YEAR));
System.out.println("月:" + (now.get(Calendar.MONTH) + 1));
System.out.println("日:" + now.get(Calendar.DAY_OF_MONTH));
System.out.println("时:" + now.get(Calendar.HOUR_OF_DAY));
System.out.println("分:" + now.get(Calendar.MINUTE));
System.out.println("秒:" + now.get(Calendar.SECOND));
//使用Date
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("当前时间:" + sdf.format(d));
复制代码

输出的结果如下:

 

posted @ 2017-03-16 00:38  EasonJim  阅读(81306)  评论(2)    收藏  举报
编辑推荐:
· 2025年:是时候重新认识System.Text.Json了
· 源码浅析:SpringBoot main方法结束为什么程序不停止
· C#性能优化:为何 x * Math.Sqrt(x) 远胜 Math.Pow(x, 1.5)
· 本可避免的P1事故:Nginx变更导致网关请求均响应400
· 还在手写JSON调教大模型?.NET 9有新玩法
阅读排行:
· 2025年:是时候重新认识System.Text.Json了
· .NET 9 的免费午餐:GZip 性能提升38.3%
· 开源新旗舰 GLM-4.5:不想刷榜,只想干活儿
· 优雅的.net REST API之FastEndpoints
· .NET 10 中的新增功能系列文章1——运行时中的新增功能
点击右上角即可分享
微信分享提示