javaAPIDate简介

mac2022-06-30  18

Date

代码一

public class Demo01Date { public static void main(String[] args) { Date date=new Date();//打印现在的时间Tue Sep 24 21:12:41 CST 2019 System.out.println(date); // System.out.println(date.getTime());//1970.1.1到现在的时间用毫秒表示。 demo01(); demo02(); } public static void demo01() { Date date=new Date(1000l);//0l表示1970.1.1日10.的时间。*****l表示距离初始时间到现在时间的转换的日期。 System.out.println(date); } public static void demo02() { Date date=new Date(); Long time= date.getTime();// System.out.println(time);//l表示1970.1.1日10.的时间。*****l表示距离初始时间到现在时间的转换的日期。 } }

代码二

public class Demo02DateFormat { //Date date=new Date(); SimpleDateFormat sdf=new SimpleDateFormat(); public static void main(String[] args) throws ParseException { SimpleDateFormat sdf=new SimpleDateFormat("yyyy~MM~dd HH~mm~ss");//形成格式(yyyy代表年,区分大小写。MM,和HH大写。) Date date=new Date(); System.out.println(date); String d=sdf.format(date);//调用format方法转换格式,返回值时String类型的 System.out.println(d); demo02(); } private static void demo02() throws ParseException { SimpleDateFormat sdf=new SimpleDateFormat("yyyy~MM~dd HH~mm~ss");//格式! Date date=sdf.parse("2019~09~24 21~40~02");//parse(String text, ParsePosition pos) // 根据格式,还原!从字符串中解析文本以产生一个 Date 。 System.out.println(date); } }

代码三(计算出生的天数)

解题思路 1.输入出生日期 2.规定格式 3.转换为对象 4.转化为标准秒(使用gettime()方法) 5.将现在的时间转化为豪秒 6.两者相减,化为天/1000/60/24/60

public class Demo03ExeBirthday { public static void main(String[] args) throws ParseException { System.out.println("请输入您的出生日期,格式为:yyyy.MM.dd"); Scanner sc=new Scanner(System.in); String birthday=sc.next(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy.MM.dd");//定义格式 Date birthDate=sdf.parse(birthday);//将输入的数据转化为Date对象 long birthdaytime=birthDate.getTime();//调用方法将Date对象变成标准秒(1970.1.1到出生日期的秒数) long currenttime=new Date().getTime();//现在时间的标准秒 System.out.print("您已经出生:"); System.out.println((Math.abs(birthdaytime - currenttime)/1000/60/24/60)+"天");//两者差转化为天数 } }
最新回复(0)