Java中Date类的使用

目录

一、获取当前时间

二、获取昨天的时间

三、Date与Date之间的比较

四、获取Date的部分信息(年、月、日)

五、Date和String的相互转换

六、Date和Calendar的相互转换

七、Date和时间戳(long)的相互转换

八、Date和时间戳(java.sql.Timestamp)的相互转换


 

一、获取当前时间

        // 1、获取当前日期直接输出
        Date today1 = new Date();
        System.out.println(today1+"   "+today1.toString());
        //Mon Jun 22 20:17:29 CST 2020   Mon Jun 22 20:17:29 CST 2020

        LocalDate today2 = LocalDate.now(); //Java 8
        System.out.println(today2+" "+today2.toString());
        //2020-06-22 2020-06-22

获取当前时间戳(毫秒级)的三种方式:

        //获取当前时间戳
        System.out.println(System.currentTimeMillis());
        System.out.println(Calendar.getInstance().getTimeInMillis());
        System.out.println(new Date().getTime());
        //1592913592149
        //1592913592150
        //1592913592151

二、获取昨天的时间

        // 2、获取昨天日期
        Date yesterday1 = new Date(new Date().getTime() - 24 * 60 * 60 * 1000);
        System.out.println(yesterday1+"  "+yesterday1.toString());
        //Sun Jun 21 20:17:29 CST 2020  Sun Jun 21 20:17:29 CST 2020

        //错误的用法:如果今天是6月1号,则得到的昨天日期是5月30号
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.toString());
        //java.util.GregorianCalendar[time=1592828249605,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=29,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2020,MONTH=5,WEEK_OF_YEAR=26,WEEK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=174,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=8,HOUR_OF_DAY=20,MINUTE=17,SECOND=29,MILLISECOND=605,ZONE_OFFSET=28800000,DST_OFFSET=0]
        calendar.add(Calendar.DATE, -1);    //calendar.set(Calendar.DATE, -1);  //使用calendar.add(Calendar.DAY_OF_MONTH, -1);估计就对了
        System.out.println(calendar.toString());
        //java.util.GregorianCalendar[time=1592741849605,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=29,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2020,MONTH=5,WEEK_OF_YEAR=26,WEEK_OF_MONTH=4,DAY_OF_MONTH=21,DAY_OF_YEAR=173,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=8,HOUR_OF_DAY=20,MINUTE=17,SECOND=29,MILLISECOND=605,ZONE_OFFSET=28800000,DST_OFFSET=0]
        Date yesterday2 = calendar.getTime();
        System.out.println(yesterday2 +" "+ yesterday2.toString());
        //Sun Jun 21 20:17:29 CST 2020  Sun Jun 21 20:17:29 CST 2020
        //正确的用法
        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(Calendar.HOUR_OF_DAY, -24);   //Calendar.HOUR_OF_DAY是24小时制,Calendar.HOUR是12小时制
        yesterday2 = calendar1.getTime();
        System.out.println(yesterday2 +" "+ yesterday2.toString());
        //Sun Jun 21 20:17:29 CST 2020  Sun Jun 21 20:17:29 CST 2020

        //使用Apache Commons Lang工具包的org.apache.commons.lang3.time.DateUtils工具类
        Date yesterday3 = DateUtils.addDays(new Date(), -1);
        System.out.println(yesterday3+" "+yesterday3.toString());
        //Sun Jun 21 20:17:29 CST 2020  Sun Jun 21 20:17:29 CST 2020

使用Apache Commons Lang工具包需要在pom.xml文件引入依赖:

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.3.2</version>
        </dependency>

三、Date与Date之间的比较

        // 3、Date与Date之间的比较
        Date date1 = new Date();
        Date date2 = new Date();
        Date date3 = DateUtils.addDays(new Date(), 1);
        int compare12 = date1.compareTo(date2);
        int compare13 = date1.compareTo(date3);
        System.out.println(compare12 +" "+ compare13);
        //0 -1

如果是LocalDate类之间的比较

        LocalDate today = LocalDate.now();  //Java 8
        LocalDate oneDay = LocalDate.of(2019, 9, 9);
        System.out.println(today+"  "+oneDay+"  "+oneDay.equals(today));
        //2020-06-22  2019-09-09  false

四、获取Date的部分信息(年、月、日)

        // 4、获取Date的年、月、日
        Date date = new Date();
        int dateDate = date.getDate();
        int dateYear = date.getYear();
        int dateMonth = date.getMonth();
        int dateDay = date.getDay();
        int dateHour = date.getHours();
        int dateMinute = date.getMinutes();
        int dateSecond = date.getSeconds();
        System.out.println(dateDate+"        "+dateYear+"/"+dateMonth+"/"+dateDay +"        "+ dateHour+"/"+dateMinute+"/"+dateSecond);
        //22        120/5/1        20/40/25

Date获取年月日的方法实际上已经废弃了,最好还是使用以下方式

        Calendar calendar2 = new GregorianCalendar();
        int year = calendar2.get(Calendar.YEAR);    //2020
        int month = calendar2.get(Calendar.MONTH);    //5
        int dayOfYear = calendar2.get(Calendar.DAY_OF_YEAR);    //174
        int dayOfMonth = calendar2.get(Calendar.DAY_OF_MONTH);    //22
        int dayOfWeek = calendar2.get(Calendar.DAY_OF_WEEK);    //2
        int weekOfMonth = calendar2.get(Calendar.WEEK_OF_MONTH);    //4
        int weekOfYear = calendar2.get(Calendar.WEEK_OF_YEAR);    //26
        //
        int hour = calendar2.get(Calendar.HOUR);    //8
        int hourOfDay = calendar2.get(Calendar.HOUR_OF_DAY);    //20
        int minute = calendar2.get(Calendar.MINUTE);    //47
        int second = calendar2.get(Calendar.SECOND);    //34
        int millisecond = calendar2.get(Calendar.MILLISECOND);    //745

如果是LocalDate类的话

        LocalDate localDate = LocalDate.now();  //Java 8
        int year2 = localDate.getYear();    //2020
        int month2 = localDate.getMonthValue();    //6
        Month month3 = localDate.getMonth();    //"JUNE"
        int day2 = localDate.getDayOfMonth();    //22
        DayOfWeek day3 = localDate.getDayOfWeek();    //"MONDAY"
        int day4 = localDate.getDayOfYear();    //174

五、Date和String的相互转换

        // 1、将Date转换成String
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      //2020-06-22 17:41:25
        // SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");           //22/6/2020
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        Date date = new Date();
        String today = sdf.format(date);
        System.out.println(today);
        //2020年06月22日 21时00分45秒

        // 2、将String转换成Date
        String  dateInString = today;
        Date newDate = null;
        try {
            newDate = sdf.parse(dateInString);
        } catch (ParseException e) {

        }
        System.out.println(newDate);
        //Mon Jun 22 21:00:45 CST 2020

SimpleDateFormat的常用表示为:

y: year
M: month
d: day in month
D: day in year
F: day of week in month (2)
E: day in week (Tuesday)
H: 0 - 23
h: 1 - 12
k: 1 - 24
K: 0 - 11
m: 分
s: 秒
S: 毫秒

六、Date和Calendar的相互转换

        //1、将Date转换成Calendar
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar.toString());
        //java.util.GregorianCalendar[time=1592831432364,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=29,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2020,MONTH=5,WEEK_OF_YEAR=26,WEEK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=174,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=10,SECOND=32,MILLISECOND=364,ZONE_OFFSET=28800000,DST_OFFSET=0]
        calendar.setTime(date);
        System.out.println(calendar.toString());
        //java.util.GregorianCalendar[time=1592831432357,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=29,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2020,MONTH=5,WEEK_OF_YEAR=26,WEEK_OF_MONTH=4,DAY_OF_MONTH=22,DAY_OF_YEAR=174,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=9,HOUR_OF_DAY=21,MINUTE=10,SECOND=32,MILLISECOND=357,ZONE_OFFSET=28800000,DST_OFFSET=0]

        //2、将Calendar转换成Date
        Date date2 = calendar.getTime();
        System.out.println(date+"   "+date2+"   "+date.equals(date2));
        //Mon Jun 22 21:10:32 CST 2020   Mon Jun 22 21:10:32 CST 2020   true

七、Date和时间戳(long)的相互转换

        // 1、将Date转换成时间戳(long)
        Date today = new Date();
        System.out.println(today.getTime());
        //1592831024568

        // 2、将时间戳(long)转换成Date
        long timestamp = today.getTime();
        Date newDate = new Date(timestamp);
        System.out.println(newDate);
        //Mon Jun 22 21:03:44 CST 2020

String和时间戳(long)之间的转换需要借助Date和时间戳(long)之间的转换,如下所示就是将String转换成时间戳(long)

        // 3、将String转换成时间戳
        String date = "2016-6-6 00:00:00";
        // 先将String转换成Date
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = null;
        try {
            date1 = simpleDateFormat.parse(date);
        } catch (ParseException e) {

        }
        // 再将Date转换成时间戳(long)
        long timestamp1 = date1.getTime() / 1000;   //秒级时间戳,10位数
        System.out.println(timestamp1 +"    "+ new Date(timestamp1).toString());
        // 1465142400    Sun Jan 18 06:59:02 CST 1970
        timestamp1 = date1.getTime();               //毫秒级时间戳,13位数
        System.out.println(timestamp1 +"    "+ new Date(timestamp1).toString());
        // 1465142400000    Mon Jun 06 00:00:00 CST 2016

补充一下时间戳相关内容:时间戳有秒级时间戳(10位)、毫秒级时间戳(13位),一般其他语言或数据库用10位秒级时间戳比较多,而Java的Date类默认的时间戳为毫秒级,这也就是为什么Date的构造函数传入秒级时间戳会得到一个奇怪的日期。

使用Java的时间戳插入MySQL的时间戳字段时,要注意先除以1000。因为MySQL默认的时间戳是秒级时间戳。

我使用的是5.6.43版本的MySQL,5.7.25版本也是如此。关于MySQL的时间戳,可以参考:https://blog.csdn.net/fsp88927/article/details/80662369

https://blog.csdn.net/weter_drop/article/details/89924451

另外,使用其他时间戳工具,也是如此,比如我们使用一些时间戳工具网站(https://tool.lu/timestamp/)转换时间戳为日期时,13位的毫秒级会得到错误的结果。

八、Date和时间戳(java.sql.Timestamp)的相互转换

        //1、将Timestamp转换成Date
        long time = System.currentTimeMillis();
        Timestamp timestamp = new Timestamp(time);
        Date date = new Date(timestamp.getTime());
        System.out.println(date);
        //Tue Jun 23 10:14:27 CST 2020

        //2、将Date转换成Timestamp
        date = new Date();
        time = date.getTime();
        //time = time / 1000;
        timestamp = new Timestamp(time);
        System.out.println(timestamp);
        //2020-06-23 10:14:27.636
        //
        date = new Date();
        time = date.getTime();
        timestamp = new Timestamp(time);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(sdf.format(timestamp));
        //2020-06-23 10:14:27

 

参考:

https://howtodoinjava.com/java/date-time/java-date-examples

https://www.javatpoint.com/java-date-to-timestamp

https://www.cnblogs.com/jpfss/p/8758621.html

https://segmentfault.com/q/1010000000667913

https://www.cnblogs.com/jpfss/p/7132424.html

https://www.iteye.com/blog/tangmingjie2009-1543166

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值