Java学习笔记-Day19 Java 日期时间类和正则表达式
一、日期时间类
1、Date类
java.util.Date类表示日期类,位于java.util
包中。Date类中很多构造方法和方法已经过时(Deprecated),不推荐使用。由于Date类对国际化支持有限,在JDK1.1之后推荐使用java.util.Calendar
类。
注意:Month(月)的值的范围为0~11。
1.1、两个没过时的构造方法
Date()
:使用当前时间构建Date对象。
//不带参数的构造方法,创建的Date日期封装了系统当前时间
Date date= new Date();
Date(long date)
:使用一个long值构建Date对象,参数是距离1970年1月1日00:00:00以来的毫秒数。
//带参数的构造方法,创建的Date日期
Date date= new Date(10000);
1.2、成员方法
public void setTime(long time)
:设置此 Date对象用来表示距离1970年1月1日00:00:00 以来的参数time的时间点,参数time为毫秒值。
Date date= new Date();
date.setTime(100000);
public long getTime()
:返回由Date对象表示的自1970年1月1日00:00:00以来的毫秒数。
Date date= new Date(100000);
long time = date.getTime();
2、Calendar类
JDK1.1版本开始,增加了Calendar类,建议使用Calendar类代替Date类。Calendar是抽象类,不能直接使用new运算符创建对象,需要使用该类的静态方法 getInstance 来获取对象实例。
注意:Month(月)的值的范围为0~11。
2.1、成员方法
2.1.1、获得实例的静态方法
static Calendar getInstance()
:使用默认时区和语言环境获得日历对象。
Calendar calendar = Calendar.getInstance();
static Calendar getInstance(Locale aLocale)
:使用指定的语言环境获得日历对象。
static Calendar getInstance(TimeZone zone)
:使用指定的时区获得日历对象。
static Calendar getInstance(TimeZone zone, Locale aLocale)
:使用指定的时区及语言环境获得日历对象。
2.1.2、字段赋值的方法
void set(int field, int value)
:为指定的日历字段设定值。
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR,2006);
void set(int year, int month, int date)
:为年月日设定值。
Calendar calendar = Calendar.getInstance();
calendar.set(2006, 10, 1);
void set(int year, int month, int date, int hourOfDay, int minute)
:为年月日时分设定值。
Calendar calendar = Calendar.getInstance();
calendar.set(2006, 10, 1, 12, 30);
void set(int year, int month, int date, int hourOfDay, int minute, int second)
:为年月日时分秒设定值。
Calendar calendar = Calendar.getInstance();
calendar.set(2006, 10, 1, 12, 30, 50);
2.1.3、获取字段值的方法
int get(int field)
:根据字段名称,返回该字段的值。
Calendar calendar = Calendar.getInstance();
calendar.set(2006, 10, 1);
//通过getTime返回Calendar对象的Date对象
Date cdate = calendar.get(Calendar.YEAR);
2.1.4、修改字段值的方法
void add(int field, int amount):根据日历的规则,将指定的时间量添加或减去给定的日历字段。
//要从当前日历的时间减去5天,您可以通过调用以下方法来实现
Calendar calendar = Calendar.getInstance();
calendar.set(2006, 10, 1);
calendar.add(Calendar.DAY_OF_MONTH, -5);
2.1.5、Calendar类与Date类之间转换的方法
(1)Calendar类转换成Date类
Date getTime()
:将日历对象转换为Date对象返回。
Calendar calendar = Calendar.getInstance();
calendar.set(2006, 10, 1);
//通过getTime返回Calendar对象转换的Date对象
Date cdate = calendar.getTime();
(2)Date类转换成Calendar类
public final void setTime(Date date)
:使用给定的Date对象设置此Calendar对象的日期时间。
Date date= new Date();
date.setTime(100000);
Calendar calendar = Calendar.getInstance();
calendar.set(2006, 10, 1);
//通过setTime设置Calendar对象的日期时间为Date对象的日期时间
calendar.setTime(date);
3、SimpleDateFormat类
在实际编程中,往往需要对时间用不同的格式进行展示。SimpleDateFormat中定义了对时间进行格式化的方法。SimpleDateFormat类继承了抽象类DateFormat,SimpleDateFormat类有一些方法是在父类中定义。
3.1、构造方法
可以自定义一个模式字符串来构建SimpleDateFormat对象。
SimpleDateFormat(String pattern)
:使用模式字符串创建对象。
SimpleDateFormat(String pattern, Locale locale)
:使用模式字符串和区域信息创建对象。
3.2、成员方法
3.2.1、格式化成字符串的方法
String format(Date date)
:把参数date格式化成以 模式字符串 为模板的字符串。
Calendar calendar = Calendar.getInstance();
calendar.set(2020, 9, 29, 15, 25, 5);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss ");
//将Date类对象格式化成字符串
String str = sdf.format(calendar.getTime());
3.2.2、解析字符串的方法
public Date parse(String source) throws ParseException
:把字符串转换成Date对象,如果格式不匹配抛出转换异常。
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDate {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss ");
///解析字符串为Date类的对象
Date date = sdf.parse("2020年10月29日 15:25:05");
}
}
4、LocalDate类
在JDK8中定义了LocalDate类,位于java.time包中,用来表示日期,默认格式是yyyy-MM-dd,该类不包含时间信息。
4.1、成员方法
4.1.1、获得LocalDate对象的静态方法
static LocalDate now()
:使用当前日期生成LocalDate对象。
//通过LocalDate的静态方法now,创建LocalDate对象
LocalDate date = LocalDate.now();
static LocalDate of(int year, int month, int dayOfMonth)
:使用年月日数值生成LocalDate对象。
//通过LocalDate的静态方法of,创建LocalDate对象
LocalDate date = LocalDate.of(2019,10,9);
4.1.2、获得字段值的方法
int getYear()
:返回年份的字段值。
int getMonthValue()
:返回月份的字段值。
int getDayOfMonth()
:返回该月天数的字段值。
//通过LocalDate的静态方法now,创建LocalDate对象
LocalDate date = LocalDate.now();
//获取LocalDate对象的各个属性
System.out.println(date.getYear()+"-"+date.getMonthValue()+"-"+date.getDayOfMonth());
5、LocalTime类
JDK8中定义了新类LocalTime用来表示时间,位于java.time包中,用来表示时间,默认格式是HH:mm:ss,该类只包含时间信息。
5.1、成员方法
5.1.1、获得LocalTime对象的静态方法
static LocalTime now()
:使用当前时间生成LocalTime对象。
//通过LocalTime的静态方法now,创建LocalTime对象
LocalTime time = LocalTime.now();
public static LocalTime of(int hour, int minute, int second)
:使用小时、分钟和秒钟数值生成LocalTime 对象。
//通过LocalTime的静态方法of,创建LocalTime对象
LocalTime time = LocalTime .of(12,30,50);
5.1.2、获得字段值的方法
int getHour()
:返回小时的字段值。
int getMinute()
:返回分钟的字段值。
int getSecond()
:返回秒钟的字段值。
//通过LocalTime的静态方法now,创建LocalTime对象
LocalTime time = LocalTime.now();
//获取LocalTime对象的各个属性
System.out.println(time.getHour()+":"+time.getMinute()+":"+time.getSecond());
6、LocalDateTime类
6.1、成员方法
6.1.1、获得LocalDateTime对象的静态方法
static LocalDateTime now()
:使用当前日期时间生成LocalDateTime对象。
//通过LocalDateTime的静态方法now,创建LocalDateTime对象
LocalDateTime datetime = LocalDateTime.now();
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute, int second)
:使用年、月、日、小时、分钟、秒钟的数值生成LocalDateTime对象。
//通过LocalDateTime的静态方法of,创建LocalDate对象
LocalDateTime datetime = LocalDateTime.of(2019,10,9,12,30,50);
6.1.2、获得字段值的方法
int getYear()
:返回年份的字段值。
int getMonthValue()
:返回月份的字段值。
int getDayOfMonth()
:返回该月天数的字段值。
int getHour()
:返回小时的字段值。
int getMinute()
:返回分钟的字段值。
int getSecond()
:返回秒钟的字段值。
//通过LocalDateTime的静态方法now,创建LocalDateTime对象
LocalDateTime datetime = LocalDateTime.now();
//获取LocalDateTime对象的各个属性
System.out.println(datetime.getYear()+"-"+datetime.getMonthValue()+"-"+datetime.getDayOfMonth()+" "+datetime.getHour()+":"+datetime.getMinute()+":"+datetime.getSecond());
7、DateTimeFormatter类
JDK8中使用DateTimeFormatter类实现格式化成字符串及解析字符串。
7.1、成员方法
7.1.1、获得DateTimeFormatter对象的静态方法
static DateTimeFormatter ofPattern(String pattern)
:指定模式字符串,生成DateTimeFormatter对象。
//通过DateTimeFormatter的静态方法ofPattern,创建DateTimeFormatter对象
DateTimeFormatter dtFormat = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
static DateTimeFormatter ofPattern(String pattern, Locale locale)
:指定模式字符串及区域信息,生成DateTimeFormatter对象。
8、通过DateTimeFormatter类实现格式化及解析
8.1、格式化成字符串的方法
LocalDate、LocalTime、LocalDateTime类都定义了format方法,都可以使用DateTimeFormatter对象进行格式化。
// 通过LocalDate的静态方法of,创建LocalDate对象
LocalDate date = LocalDate.of(2019, 10, 9);
// 通过LocalTime的静态方法of,创建LocalTime对象
LocalTime time = LocalTime.of(20, 10, 15);
// 通过LocalDateTime的静态方法of,创建LocalDateTime对象
LocalDateTime datetime = LocalDateTime.of(2019, 10, 9, 20, 10, 15);
// 通过DateTimeFormatter的静态方法ofPattern,创建DateTimeFormatter对象
DateTimeFormatter dtFormat1 = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
// 通过DateTimeFormatter的静态方法ofPattern,创建DateTimeFormatter对象
DateTimeFormatter dtFormat2 = DateTimeFormatter.ofPattern("HH时mm分ss秒");
// 通过DateTimeFormatter的静态方法ofPattern,创建DateTimeFormatter对象
DateTimeFormatter dtFormat3 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
// 使用DateTimeFormatter对象对LocalDate对象进行格式化
String str1 = date.format(dtFormat1);
// 使用DateTimeFormatter对象对LocalTime对象进行格式化
String str2 = time.format(dtFormat2);
// 使用DateTimeFormatter对象对LocalDateTime对象格式化
String str3 = datetime.format(dtFormat3);
8.2、解析字符串的方法
LocalDate、LocalTime、LocalDateTime类都定义了parse方法,可以使用DateTimeFormatter对象把字符串按照指定的格式转换成时间日期类型对象。
String str1 = "2019年10月09日";
String str2 = "20时10分15秒";
String str3 = "2019年10月09日 20时10分15秒";
// 通过DateTimeFormatter的静态方法ofPattern,创建DateTimeFormatter对象
DateTimeFormatter dtFormat1 = DateTimeFormatter.ofPattern("yyyy年MM月dd日"); // 通过DateTimeFormatter的静态方法ofPattern,创建DateTimeFormatter对象
DateTimeFormatter dtFormat2 = DateTimeFormatter.ofPattern("HH时mm分ss秒"); // 通过DateTimeFormatter的静态方法ofPattern,创建DateTimeFormatter对象
DateTimeFormatter dtFormat3 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH时mm分ss秒");
// 使用LocalDate的parse方法解析字符串
LocalDate date = LocalDate.parse(str1, dtFormat1);
// 使用LocalTime的parse方法解析字符串
LocalTime time = LocalTime.parse(str2, dtFormat2);
// 使用LocalDateTime的parse方法解析字符串
LocalDateTime datetime = LocalDateTime.parse(str3, dtFormat3);
二、正则表达式
正则表达式(regular expression)就是用来描述字符串逻辑规则的工具。正则表达式是由元字符组成的字符串。
要使用正则表达式,首先要学会根据规则编写正则表达式。
1、常用元字符
元字符 | 含义 |
---|---|
x | 字符 x |
\\ | 反斜线字符 |
\0n | 带有八进制值 0 的字符 n (0 <= n <= 7) |
\0nn | 带有八进制值 0 的字符 nn (0 <= n <= 7) |
\0mnn | 带有八进制值 0 的字符 mnn(0 <= m <= 3、0 <= n <= 7) |
\xhh | 带有十六进制值 0x 的字符 hh |
\uhhhh | 带有十六进制值 0x 的字符 hhhh |
\t | 新行(换行)符 (’\u000A’) |
\r | 回车符 (’\u000D’) |
\f | 换页符 (’\u000C’) |
\a | 报警 (bell) 符 (’\u0007’) |
\e | 转义符 (’\u001B’) |
\cx | 对应于 x 的控制符 |
[abc] | a、b 或 c(简单类) |
[^abc] | 任何字符,除了 a、b 或 c(否定) |
[a-zA-Z] | a 到 z 或 A 到 Z,两头的字母包括在内(范围) |
[a-d[m-p]] | a 到 d 或 m 到 p,等同于:[a-dm-p](并集) |
[a-z&&[def]] | d、e 或 f(交集) |
[a-z&&[^bc]] | a 到 z,除了 b 和 c,等同于c:[ad-z](减去) |
[a-z&&[^m-p]] | a 到 z,而非 m 到 p,等同于:[a-lq-z](减去) |
. | 任何字符(与行结束符可能匹配也可能不匹配) |
\d | 数字,等同于:[0-9] |
\D | 非数字,等同于: [^0-9] |
\s | 空白字符,等同于:[ \t\n\x0B\f\r] |
\S | 非空白字符,等同于:[^\s] |
\w | 单词字符,等同于:[a-zA-Z_0-9] |
\W | 非单词字符,等同于:[^\w] |
^ | 行的开头 |
$ | 行的结尾 |
\b | 单词边界 |
\B | 非单词边界 |
\A | 输入的开头 |
\G | 上一个匹配的结尾 |
\Z | 输入的结尾,仅用于最后的结束符(如果有的话) |
\z | 输入的结尾 |
2、常用量词
元字符 | 含义 |
---|---|
X? | X,零次或一次 |
X* | X,零次或多次 |
X+ | X,一次或多次 |
X{n} | X,恰好 n 次 |
X{n,} | X,至少 n 次 |
X{n,m} | X,至少 n 次,但是不超过 m 次 |
3、使用正则表达式
3.1、方式一
使用Pattern的静态方法compile(String regex)方法把正则表达式编译成Pattern对象,使用Pattern的matcher方法为待匹配的字符串生成Matcher对象,使用Matcher对象的matches方法进行匹配判断。
Pattern的静态方法compile的源码:
public static Pattern compile(String regex) {
return new Pattern(regex, 0);
}
Pattern的matcher方法的源码:
public Matcher matcher(CharSequence input) {
if (!compiled) {
synchronized(this) {
if (!compiled)
compile();
}
}
Matcher m = new Matcher(this, input);
return m;
}
Matcher的matches方法的源码:
public boolean matches() {
return match(from, ENDANCHOR);
}
示例1:
//以字符串形式定义正则表达式regex
String regex = "1[3579]\\w[0-9]{9}";
//需要进行匹配的字符串
String str = "138503221222";
//方式一
//使用Pattern.compile方法把正则表达式编译成Pattern对象
Pattern p = Pattern.compile(regex);
//使用Pattern的matcher方法为待匹配的字符串生成Matcher对象
Matcher m = p.matcher(str);
//使用Matcher对象的matches方法进行匹配判断
boolean flag = m.matches();
System.out.println(flag);
示例2:
//以字符串形式定义正则表达式regex
String regex = "1[3579]\\w[0-9]{9}";
//需要进行匹配的字符串
String str = "138503221222";
boolean flag = Pattern.compile(regex).matcher(str).matches();
System.out.println(flag);
3.2、方式二
使用Pattern的静态方法matches(regex, input)直接进行匹配。
Pattern的静态方法matches的源码:
public static boolean matches(String regex, CharSequence input) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
return m.matches();
}
示例:
//使用Pattern的静态方法matches(regex, input)直接进行匹配
boolean flag = Pattern.matches(regex,str);
System.out.println(flag);
3.3、方式三
使用String的成员方法matches(regex)直接进行匹配。
String类的matches方法源码:
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
示例:
//以字符串形式定义正则表达式regex
String regex = "1[3579]\\w[0-9]{9}";
//需要进行匹配的字符串
String str = "138503221222";
//使用String的成员方法matches(regex)直接进行匹配
Boolean flag = str.matches(regex);
System.out.println(flag);
三、其它类与接口
1、BigInteger类
Java中整数的最大范围是long类型(64位),如果需要使用超过long类型范围的整数,可以使用BigInteger类。BigInteger是不可变的任意精度整数,位于java.math
包中,BigInteger只能通过调用该类中的数学运算方法进行计算,不能使用运算符进行计算。
1.1、步骤
(1)将超出long类型范围的整数用String声明。
(2)将字符串包装成BigInteger对象。
(3)调用BigInteger类的方法,进行数学运算。
String s1 = "12345687954125256151";
String s2 = "15646456151565123231121";
BigInteger bi1 = new BigInteger(s1);
BigInteger bi2 = new BigInteger(s2);
System.out.println(bi1.add(bi2));//15658801839519248487272
2、BigDecimal类
BigDecimal是不变的、任意精度的带符号的十进制数字,位于java.math
包中。BigDecimal是用来针对浮点型进行精确运算的。需要精确计算的时候使用,一般用于商业运算。
double d1 = 10.5;
double d2 = 23.6;
//输出的值为34.1
System.out.println(d1+d2);
BigDecimal bd1 = new BigDecimal(d1);
BigDecimal bd2 = new BigDecimal(d2);
//输出的值为34.10000000000000142108547152020037174224853515625
System.out.println(bd1.add(bd2));
3、UUID类
UUID是通用唯一识别码 (Universally Unique Identifier)的缩写,是唯一的机器生成的标识符。UUID都不能是人工生成的,这样风险太高。UUID是128位长的数字,通常以36字节的字符串表示,示例如下:3F2504E0-4F89-11D3-9A0C-0305E82C3301
,通常在分布式系统中用来生成唯一ID。
Java中对UUID的生成提供了支持,java.util.UUID
类定义了生成UUID的方法。
//生成UUID
UUID uuid = UUID.randomUUID();
System.out.println(uuid);
/* 程序运行后,每次生成的UUID都是不同的
* 309b7db2-0f12-476d-b276-74cf83d7dcd9
* 1fdb044a-cd71-417e-91e8-d44f729e7fbb
* 82944c84-88d8-4304-b544-e96024a56580
* 2b2d9707-cb76-40cc-b331-de797f41479e
* ee330a8a-9fc9-4cae-bf1c-39532d05da98
* 269c2b9f-df19-49db-b103-047c81a9b40d
* e9c1d7b3-c09a-4d26-b7cc-0f85462b9459
* dc561ae4-b902-4a96-b225-c393c9fa8e98
* 75f3f0b0-f611-4828-b806-dd0a97f52b12
* 3a751dae-99c2-4cda-b7d3-f92da0035bd7
*/
4、Charsequence接口
Charsequence是一个接口,表示char值的一个可读序列,位于java.lang
包中。此接口对许多不同种类的char序列提供统一的自读访问。String、StringBuffer、StringBuilder都是它的实现类。