【Java例题】6.2 日期类的使用
2.日期类的使用。
显示今天的年月日、时分秒和毫秒数。
显示今天是星期几、是今年内的第几天。
显示本月共几天,今年是不是闰年。
显示两个日期的差,包括年月日、时分秒和毫秒差值。
package chapter6; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class demo2 { static public void main(String[] args) throws ParseException { Calendar now = Calendar.getInstance(); System.out.print("年: " + now.get(Calendar.YEAR)); System.out.print(" 月: " + (now.get(Calendar.MONTH)+1)); System.out.print(" 日: " + now.get(Calendar.DAY_OF_MONTH)); System.out.print(" 时: " + now.get(Calendar.HOUR_OF_DAY)); System.out.print(" 分: " + now.get(Calendar.MINUTE)); System.out.print(" 秒: " + now.get(Calendar.SECOND)); System.out.println (" 当前时间毫秒数:" + now.getTimeInMillis()); String[] weekDays = {"", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六",}; int w = now.get(Calendar.DAY_OF_WEEK); System.out.print(weekDays[w]); System.out.println(" 今年第 " + now.get(Calendar.DAY_OF_YEAR)+"天"); int maxDay = now.getActualMaximum(java.util.Calendar.DAY_OF_MONTH); System.out.print("本月共"+maxDay+"天"); int year=now.get(Calendar.YEAR); System.out.println((year%4==0&&year%100!=0)||(year%400==0)?" 闰年":" 不是闰年"); Scanner sc=new Scanner(System.in); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); System.out.println("请输入yyyy-MM-dd格式的年月日1(较大)"); String inputday1 = sc.next(); System.out.println("请输入yyyy-MM-dd格式的年月日2(较小)"); String inputday2 = sc.next(); Date theday1=new Date(); Date theday2=new Date(); theday1=format.parse(inputday1); theday2=format.parse(inputday2); int day=(int) ((theday1.getTime()-theday2.getTime())/(24*60*60*1000)); int hour=(int) ((theday1.getTime()-theday2.getTime())/(60*60*1000)); int min=(int) ((theday1.getTime()-theday2.getTime())/(60*1000)); int sec=(int) ((theday1.getTime()-theday2.getTime())/(1000)); double ms=(double) (theday1.getTime()-theday2.getTime()); int mouth=day/30; int year1=mouth/12; System.out.print("差"+year1+"年 "); System.out.print("差"+mouth+"月 "); System.out.print("差"+day+"天 "); System.out.print("差"+hour+"时 "); System.out.print("差"+min+"分 "); System.out.print("差"+sec+"秒 "); System.out.print("差"+ms+"毫秒 "); sc.close(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix