【Java 日期相关类】

78 篇文章 0 订阅

java.util.Date

package com.yuzhenc.common;

import java.util.Date;

/**
 * @author: yuzhenc
 * @date: 2022-02-27 16:56:27
 * @desc: com.yuzhenc.common
 * @version: 1.0
 */
public class Test02 {
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println(date);//Sun Feb 27 17:13:44 CST 2022
        System.out.println(date.toGMTString());//27 Feb 2022 09:13:44 GMT
        System.out.println(date.toLocaleString());//2022-2-27 17:13:44
        System.out.println(date.getYear());//122
        System.out.println(date.getMonth());//1
        返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数
        System.out.println(date.getTime());//1645953224265
        System.out.println(System.currentTimeMillis());//1645953224284
        /*
        (1)疑问:以后获取时间差用:getTime()还是currentTimeMillis()
        答案:currentTimeMillis()--》因为这个方法是静态的,可以类名.方法名直接调用
        (2)public static native long currentTimeMillis();
        本地方法
        为什么没有方法体?因为这个方法的具体实现不是通过java写的。
        (3)这个方法的作用:
        一般会去衡量一些算法所用的时间
         */
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {

        }
        long endTime = System.currentTimeMillis();
        System.out.println(endTime-startTime);//6
    }
}

在这里插入图片描述

java.sql.Date

package com.yuzhenc.common;

import java.sql.Date;

/**
 * @author: yuzhenc
 * @date: 2022-02-27 17:17:45
 * @desc: com.yuzhenc.common
 * @version: 1.0
 */
public class Test03 {
    public static void main(String[] args) {
        /*
        (1)java.sql.Date和java.util.Date的区别:
            java.util.Date:年月日  时分秒
            java.sql.Date:年月日
        (2)java.sql.Date和java.util.Date的联系:
            java.sql.Date(子类) extends java.util.Date (父类)
         */
        java.util.Date date = new Date(System.currentTimeMillis());//父类引用指向子类对象
        //java.sql.Date转java.util.Date
        //向下转型
        Date sqlDate = (Date)date;
        //利用构造器转化
        sqlDate = new Date(date.getTime());
        //java.util.Date转java.sql.Date
        date = sqlDate;//向上转型
        //String转java.sql.Date
        sqlDate = Date.valueOf("2022-02-27");
        System.out.println(sqlDate);//2022-02-27
        System.out.println(date);//2022-02-27
    }
}

SimpleDateFormat

package com.yuzhenc.common;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: yuzhenc
 * @date: 2022-02-27 17:38:48
 * @desc: com.yuzhenc.common
 * @version: 1.0
 */
public class Test04 {
    public static void main(String[] args) {
        //格式化日期
        //定义一个格式 yyyy-MM-dd HH:mm:ss.SSS
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        //Date转String
        String format = df.format(new Date());
        System.out.println(format);//2022-02-27 17:58:56.007
        //String转Date
        try {
            Date d = df.parse("2022-02-27 17:57:20.123");
            System.out.println(d);//Sun Feb 27 17:57:20 CST 2022
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
Date and Time PatternResult
“yyyy.MM.dd G ‘at’ HH:mm:ss z”2001.07.04 AD at 12:08:56 PDT
“EEE, MMM d, ''yy”Wed, Jul 4, '01
“h:mm a”12:08 PM
“hh ‘o’‘clock’ a, zzzz”12 o’clock PM, Pacific Daylight Time
“K:mm a, z”0:08 PM, PDT
“yyyyy.MMMMM.dd GGG hh:mm aaa”02001.July.04 AD 12:08 PM
“EEE, d MMM yyyy HH:mm:ss Z”Wed, 4 Jul 2001 12:08:56 -0700
“yyMMddHHmmssZ”010704120856-0700
“yyyy-MM-dd’T’HH:mm:ss.SSSZ”2001-07-04T12:08:56.235-0700
“yyyy-MM-dd’T’HH:mm:ss.SSSXXX”2001-07-04T12:08:56.235-07:00
“YYYY-'W’ww-u”2001-W27-3

在这里插入图片描述

Calendar

package com.yuzhenc.common;

import java.sql.Date;
import java.util.Calendar;

/**
 * @author: yuzhenc
 * @date: 2022-02-27 18:03:10
 * @desc: com.yuzhenc.common
 * @version: 1.0
 */
public class Test05 {
    public static void main(String[] args) {
        //给定date字符串
        String strDate = "2022-10-28";
        //实例化一个Date
        Date date = Date.valueOf(strDate);
        //Date转为Calendar
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        //月份
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1; //从0开始,所以+1
        System.out.println(year + "-" + month + ":");
        //星期提示
        System.out.println("日\t一\t二\t三\t四\t五\t六\t");
        //获取本月的最大天数
        int maxDay = cal.getActualMaximum(Calendar.DATE);
        //获取当前日期中的日
        int nowday = cal.get(Calendar.DATE);
        //将日期调为本月1号
        cal.set(Calendar.DATE,1);
        //获取1号是本周的第几天
        int num = cal.get(Calendar.DAY_OF_WEEK);
        //计数器
        int count = 0;
        //输出空格
        for (int i = 1; i < num; i++) {
            System.out.print("\t");
        }
        count = count + num;
        //从1号到maxDay号进行遍历
        for (int i = 1; i <= maxDay; i++) {
            if (i == nowday) {
                System.out.print(i+"*"+"\t");
            } else {
                System.out.print(i+"\t");
            }
            if (count%7 == 0) {
                System.out.println();
            }
            count ++;
        }
    }
}

在这里插入图片描述

LocalDate/LocalTime/LocalDateTime

package com.yuzhenc.common;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * @author: yuzhenc
 * @date: 2022-02-27 18:08:37
 * @desc: com.yuzhenc.common
 * @version: 1.0
 */
public class Test06 {
    public static void main(String[] args) {
        //实例化
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate);//2022-02-27
        LocalTime localTime = LocalTime.now();
        System.out.println(localTime);//18:30:12.858
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime);//2022-02-27T18:30:12.858

        //设置指定时间
        LocalDate localDate1 = LocalDate.of(2022,2,27);
        System.out.println(localDate1);//2022-02-27
        LocalTime localTime1 = LocalTime.of(18,13,59,123);
        System.out.println(localTime1);//18:13:59.000000123
        LocalDateTime localDateTime1 = LocalDateTime.of(2022,2,27,18,16,50,959154125);
        System.out.println(localDateTime1);//2022-02-27T18:16:50.959154125

        //常用get方法
        System.out.println(localDateTime.getYear());//2022
        System.out.println(localDateTime.getMonth());//FEBRUARY
        System.out.println(localDateTime.getMonthValue());//2
        System.out.println(localDateTime.getDayOfMonth());//27
        System.out.println(localDateTime.getDayOfWeek());//SUNDAY
        System.out.println(localDateTime.getHour());//18
        System.out.println(localDateTime.getMinute());//21
        System.out.println(localDateTime.getSecond());//4

        //不可变性
        //设置月份为8,不是set
        LocalDateTime localDateTime2 = localDateTime.withMonth(8);
        System.out.println(localDateTime);//2022-02-27T18:19:28.048
        System.out.println(localDateTime2);//2022-08-27T18:19:28.048

        //时间加减
        //加
        LocalDateTime localDateTime3 = localDateTime.plusMonths(8);
        System.out.println(localDateTime);//2022-02-27T18:30:12.858
        System.out.println(localDateTime3);//2022-10-27T18:30:12.858
        //减
        LocalDateTime localDateTime4 = localDateTime.minusMinutes(8);
        System.out.println(localDateTime);//2022-02-27T18:30:12.858
        System.out.println(localDateTime4);//2022-02-27T18:22:12.858
    }
}

DateTimeFormatter

package com.yuzhenc.common;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;

/**
 * @author: yuzhenc
 * @date: 2022-02-27 18:35:39
 * @desc: com.yuzhenc.common
 * @version: 1.0
 */
public class Test07 {
    public static void main(String[] args) {
        //格式化类 DateTimeFormatter

        //方式一:预定义的标准格式。如: ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;IS0_LOCAL_TIME
        DateTimeFormatter df = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //LocalDateTime转String
        LocalDateTime localDateTime = LocalDateTime.now();
        String str = df.format(localDateTime);
        System.out.println(str);//2022-02-27T18:39:41.098
        //String转LocalDateTime
        TemporalAccessor parse = df.parse("2022-02-27T18:39:41.098");
        System.out.println(parse);//{},ISO resolved to 2022-02-27T18:39:41.098

        //方式二:本地化相关的格式。如: ofLocalizedDateTime()
        //参数:FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT
        //FormatStyle.LONG :2020年6月15日 下午03时17分13秒
        //FormatStyle.MEDIUM: 2020-6-15 15:17:42
        //FormatStyle.SHORT:20-6-15 下午3:18
        DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        //LocalDateTime转String
        LocalDateTime localDateTime1 = LocalDateTime.now();
        String str1 = df1.format(localDateTime1);
        System.out.println(str1);//2022年2月27日 下午06时47分19秒
        //String转LocalDateTime
        TemporalAccessor parse1 = df1.parse("2022年2月27日 下午06时47分19秒");
        System.out.println(parse1);//{},ISO resolved to 2022-02-27T18:47:19

        //方式三: 自定义的格式。如: ofPattern( "yyyy-MM-dd hh:mm:ss") ---》重点,以后常用
        DateTimeFormatter df2 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss.SSS");
        //LocalDateTime转String
        LocalDateTime localDateTime2 = LocalDateTime.now();
        String str2 = df2.format(localDateTime2);
        System.out.println(str2);//2022-02-27 07:09:32.420
        //String转LocalDateTime
        TemporalAccessor parse2 = df2.parse("2022-02-27 07:09:32.420");
        System.out.println(parse2);//{MinuteOfHour=9, HourOfAmPm=7, MilliOfSecond=420, MicroOfSecond=420000, SecondOfMinute=32, NanoOfSecond=420000000},ISO resolved to 2022-02-27
    }
}
FormatterDescriptionExample
BASIC_ISO_DATEBasic ISO date‘20111203’
ISO_LOCAL_DATEISO Local Date‘2011-12-03’
ISO_OFFSET_DATEISO Date with offset‘2011-12-03+01:00’
ISO_DATEISO Date with or without offset‘2011-12-03+01:00’; ‘2011-12-03’
ISO_LOCAL_TIMETime without offset‘10:15:30’
ISO_OFFSET_TIMETime with offset‘10:15:30+01:00’
ISO_TIMETime with or without offset‘10:15:30+01:00’; ‘10:15:30’
ISO_LOCAL_DATE_TIMEISO Local Date and Time‘2011-12-03T10:15:30’
ISO_OFFSET_DATE_TIMEDate Time with Offset2011-12-03T10:15:30+01:00’
ISO_ZONED_DATE_TIMEZoned Date Time‘2011-12-03T10:15:30+01:00[Europe/Paris]’
ISO_DATE_TIMEDate and time with ZoneId‘2011-12-03T10:15:30+01:00[Europe/Paris]’
ISO_ORDINAL_DATEYear and day of year‘2012-337’
ISO_WEEK_DATEYear and Week2012-W48-6’
ISO_INSTANTDate and Time of an Instant‘2011-12-03T10:15:30Z’
RFC_1123_DATE_TIMERFC 1123 / RFC 822‘Tue, 3 Jun 2008 11:05:30 GMT’
SymbolMeaningPresentationExamples
GeratextAD; Anno Domini; A
uyearyear2004; 04
yyear-of-erayear2004; 04
Dday-of-yearnumber189
M/Lmonth-of-yearnumber/text7; 07; Jul; July; J
dday-of-monthnumber10
Q/qquarter-of-yearnumber/text3; 03; Q3; 3rd quarter
Yweek-based-yearyear1996; 96
wweek-of-week-based-yearnumber27
Wweek-of-monthnumber4
Eday-of-weektextTue; Tuesday; T
e/clocalized day-of-weeknumber/text2; 02; Tue; Tuesday; T
Fweek-of-monthnumber3
aam-pm-of-daytextPM
hclock-hour-of-am-pm (1-12)number12
Khour-of-am-pm (0-11)number0
kclock-hour-of-am-pm (1-24)number0
Hhour-of-day (0-23)number0
mminute-of-hournumber30
ssecond-of-minutenumber55
Sfraction-of-secondfraction978
Amilli-of-daynumber1234
nnano-of-secondnumber987654321
Nnano-of-daynumber1234000000
Vtime-zone IDzone-idAmerica/Los_Angeles; Z; -08:30
ztime-zone namezone-namePacific Standard Time; PST
Olocalized zone-offsetoffset-OGMT+8; GMT+08:00; UTC-08:00;
Xzone-offset ‘Z’ for zerooffset-XZ; -08; -0830; -08:30; -083015; -08:30:15;
xzone-offsetoffset-x+0000; -08; -0830; -08:30; -083015; -08:30:15;
Zzone-offsetoffset-Z+0000; -0800; -08:00;
ppad nextpad modifier1
escape for textdelimiter
‘’single quoteliteral
[optional section start
]optional section end
#reserved for future use
{reserved for future use
}reserved for future use
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sqlboy-yuzhenc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值