概述
Java Util类
字符串
类型转化
//将其他类型转化为字符串类型
int a = 1234567;
String val = String.valueOf(a);
System.out.println(val);
String str = "1234567";
System.out.println(Integer.parseInt(str));
构造方法
String a = "abc";
String b = new String(“abc”).intern();
String c = new String("abc");
String d = new String(new char[]{'a','b','c'});
String e = new String(new byte[]{21,123,45,-128,127});
System.out.println(e);
静态方法
格式化输出
//格式化字符输出
String name = "henry";
char gender = '男';
int age = 18;
double salary = 31415.926;
//String.format
System.out.println(String.format("%s,%c,%d,%.2f",name,gender,age,salary));
//Message.format效率最高(可复用)
System.out.println(MessageFormat.format("{0},{1},{0},{2},{3}",name,gender,age,salary));
//使用+进行字符串拼接
System.out.println(name + "," + gender + "," + age + "," + salary);
字符串拼接
//大量未知内容拼接字符串
//StringBuilder
String[] strs = {"henry","pola","ariel","rose","jack","sherry","jerry","tom"}
StringBuilder builder = new StringBuilder();
for(String str : strs){
builder.append(str);
builder.append(',')
}
builder.deleteCharAt(builder.length()-1);
System.out.println(builder);
//StringJoiner
StringJoiner sj = new StringJoiner(",","Hello","!");
for(String str : strs){
sj.add(str);
}
System.out.println(sj.toString());
String sj2 = String.join(",",strs);
System.out.println(sj2);
对象方法
字符串比较
//比较
String str1 = "I love you";
String str2 = "I like you";
String str3 = "i love you";
boolean equals = str1.equals(str2);
System.out.println(equals);
boolean equals2 = str1.equalsIgnoreCase(str3);
System.out.println(equals2);
包含
String email = "henry.chen@zbitedu.cn"
//String是否以prefix开始,或以suffix结尾
System.out.println(email.startWith("henry"));
System.out.println(email.endWith("cn"));
//contains
System.out.println(email.contains("chen"));
匹配
//matches
System.out.println(email.matches("(\w{3,}|\w{2,}\.\w{2,})@[0-9a-zA-Z]{2,}\.(com|cn|com\.cn|net|org)"));
截取
//获取指定下标未知字符
char sign = email.charAt(3);
System.out.println(sign);
String name = email.substring(email.indexOf('@') + 1);
System.out.println(name);
String firstName = email.substring(email.indexOf('.')+1,email.indexOf('@'));
System.out.println(firstName);
查找
int i = email.indexOf('@');
Sysetm.out.println(i);
//指定起始位置
int i2 = email.indexOf('.',email.indexOf(".")+1);
System.out.println(i2);
分割
//多符号分割
String[] strs1 = email.split("\.|@");
for(String s : strs2){
System.out.println(s);
}
替换
String s1 = email.replace('c','d');
System.out.println(s1);
String s2 = email.replace("(e|h)","A");
System.out.println(s2);
String s3 = email.replaceAll("(e|h)","#");
System.out.println(s3);
String s4 = email.replaceFirst("(e|h)","#");
System.out.println(s4);
其他
//大小写转换
System.out.println(email.toUpperCase());
System.out.println(email.toLowerCase());
//修剪
String str = " trim to size ";
str = str.trim();
System.out.println(str);
System.out.println(email.isEmpty());
System.out.println(email.length());
枚举类型
static enum Gender Student{
private String name;
private Gender gender;
public Student(String name,Gender gender){
this.name = name;
this.gender = gender;
}
}
public static void main(String[] args) throws ParseException{
Student stu = new Student("henry", Gender.MALE);
System.out.println(stu);
System.out.println(Gender.MALE);
System.out.println(Gender.MAILE.ordinal());
}
日期
日期类的本质:long 纪元至此刻的毫秒数
//Instant 时间戳类
Instant now = Instant.now();
System.out.println(now.getEpochSecond());
System.out.println(now.toEpochMilli());
//给时间戳Instant关联上一个时区就可以创建出ZoneDateTime
Instant ins = Instant.ofEpochSecond(1568568760);
ZonedDateTime zdt = ins.atZone(ZoneId.systemDefault());
System.out.println(zdt);
//Date 日期类
Date date = new Date();
System.out.println(date);
System.out.println(date.getTime()); //获取指定日期对象的时间戳
Date time = new Date(1);
System.out.println("time: " + time); //根据指定的时间戳生成日期
int rst = time.compareTo(date); //时间比较
System.out.println(rst);
System.out.println(date.equals(time));
System.out.println(date.after(time));
System.out.println(date.before(time));
//将日期对象格式化为指定格式的字符串
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
System.out.println(sdf.format(date));
//将【符合指定格式】的字符串解析为日期对象
String time = "2020-10-13 10:11:12 13";
Date _date = sdf.parse(time);
System.out.println(_date);
System.out.println(_date.getTime());
日历类
Calendar c = Calendar.getInstance();
c.set(2018,5,18,0,0,0);
c.setTimeInMillis(114456787654L);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
String _time = "2020-10-13 10:11:12 13";
Date _date = sdf.parse(_time);
c.setTime(_date);
System.out.println(c);
Date time = c.getTime();
System.out.println(time);
c.set(Calendar.YEAR, 2021);
c.set(Calendar.MONTH, 3);
c.set(Calendar.DATE, 27);
c.set(Calendar.HOUR, 11);
c.set(Calendar.MINUTE, 13);
c.set(Calendar.SECOND, 22);
int month = c.get(Calendar.MONTH) + 1;
System.out.println("Month:" + month);
//季度
int quarter = (month - 1 )/3+1;
System.out.println("quarter: " + quarter);
//年周
int weekYear = c.get(Calendar.WEEK_OF_YEAR);
System.out.println("weekYear: " + weekYear);
//月周
int weekMonth = c.get(Calendar.WEEK_OF_MONTH);
System.out.println("weekMonth: " + weekMonth);
//周几 周日~周六 1~7
int weekDay = c.get(Calendar.DAY_OF_WEEK);
System.out.println("weekDay: " + weekDay);
c.roll(Calendar.YEAR, -3);
c.add(Calendar.YEAR, 2);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
System.out.println(sdf.format(c.getTime()));
时区
TimeZone tzDefault = TimeZone.getDefault();
TimeZone tzGMT9 = TimeZone.getTimeZone("GMT+9:00");
TimeZone tzNY = TimeZone.getTimeZone("America/New_York");
System.out.println(tzDefault.getID());
System.out.println(tzGMT9.getID());
System.out.println(tzNY.getID());
利用Calendar进行时区转换
Calendar c = Calendar.getInstance();
c.clear();
c.set(2019, 10*//* 11月 *//*, 20, 8, 15, 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(sdf.format(c.getTime()));
从java8开始新加入的API
LocalDateTime
LocalDate d = LocalDate.now();
LocalTime t = LocalTime.now();
LocalDateTime dt = LocalDateTime.now();
System.out.println(d);
System.out.println(t);
System.out.println(dt);
//转换
LocalDateTime dt = LocalDateTime.now();
LocalDate d = dt.toLocalDate();
LocalTime t = dt.toLocalTime();
//指定日期和时间
LocalDate d2 = LocalDate.of(2019,11,30);
LocalTime t2 = LocalTime.of(15,16,17);
LocalDateTime dt2 = LocalDateTime.of(2019,11,30,15,16,17);
LocalDateTime dt3 = LocalDateTime.of(d2, t2);
//字符串传入
LocalDateTime dt = LocalDateTime.parse("2019-11-19T15:16:17");
LocalDate d = LocalDate.parse("2019-11-19");
LocalTime t = LocalTime.parse("15:16:17");
System.out.println(dt);
//DateTimeFormatter
//自定义格式化
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
System.out.println(dtf.format(LocalDateTime.now()));
//自定义格式解析
LocalDateTime dt2 = LocalDateTime.parse("2019/11/30 15:16:17", dtf);
System.out.println(dt2);
//日子加减链式调用
LocalDateTime dt = LocalDateTime.of(2019,10, 26, 20, 30, 59);
System.out.println(dt);
LocalDateTime dt2 = dt.plusDays(5).minusHours(3);
System.out.println(dt2);
LocalDateTime dt3 = dt2.minusMonths(1);
System.out.println(dt3);
//日期调整 with
LocalDateTime dt = LocalDateTime.of(2019, 10, 26, 20, 30, 59);
System.out.println(dt);
LocalDateTime dt2 = dt.withDayOfMonth(31);
System.out.println(dt2);
LocalDateTime dt3 = dt2.withMonth(9);
System.out.println(dt3);
//本月第一天0:00时刻:
LocalDateTime firstDay = LocalDate.now().withDayOfMonth(1).atStartOfDay();
System.out.println(firstDay);
//本月最后1天;
LocalDate lastDay = LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
System.out.println(lastDay);
//下月第1天:
LocalDate nextMonthFirstDay = LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth());
System.out.println(nextMonthFirstDay);
//本月第1个周一
LocalDate firstWeekday = LocalDate.now().with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
System.out.println(firstWeekday);
//判断时间先后
LocalDateTime now = LocalDateTime.now();
LocalDateTime target = LocalDateTime.of(2019, 11, 19,8,15,0);
System.out.println(now.isBefore(target));
System.out.println(LocalDate.now().isBefore(LocalDate.of(2019, 11, 19)));
System.out.println(LocalTime.now().isAfter(LocalTime.parse(("08:15:00"))));
//Duration 和 Period
LocalDateTime start = LocalDateTime.of(2019, 11, 19, 8, 15, 0);
LocalDateTime end = LocalDateTime.of(2020, 1,9,19,25,30);
Duration d = Duration.between(start, end);
System.out.println(d);
Period p = LocalDate.of(2019, 11, 19).until(LocalDate.of(2020, 1, 9));
System.out.println(p);
//直接创建
Duration d1 = Duration.ofHours(10);
Duration d2 = Duration.parse("P1DT2H3M");
System.out.println(d1);
System.out.println(d2);
ZoneDateTime
ZonedDateTime zbj = ZonedDateTime.now();
ZonedDateTime zny = ZonedDateTime.now(ZoneId.of("America/New_York"));
System.out.println(zbj);
System.out.println(zny);
//ZoneId
//给LocalDateTime附加ZoneID,变成ZoneDateTime
LocalDateTime ldt = LocalDateTime.of(2019, 9, 15, 16, 17);
ZonedDateTime zbj = ldt.atZone(ZoneId.systemDefault());
ZonedDateTime zny = ldt.atZone(ZoneId.of("America/New_York"));
System.out.println(zbj);
System.out.println(zny);
//时区转换
ZonedDateTime zbj = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
ZonedDateTime zny = zbj.withZoneSameInstant(ZoneId.of("America/New_York"));
System.out.println(zbj);
System.out.println(zny);
//练习,某航线从北京飞到纽约需要13小时20分钟,请根据北京起飞日期和时间计算到
//纽约的当地日期和时间
LocalDateTime departureAtBeijing = LocalDateTime.of(2019, 9, 15, 13, 0, 0);
int hours = 13;
int minutes = 20;
LocalDateTime arrivalAtNewYork = calculateArrivalAtNY(departureAtBeijing, hours, minutes);
System.out.println(departureAtBeijing + " -> " + arrivalAtNewYork);
//test
if (!LocalDateTime.of(2019, 10, 15, 14, 20, 0)
.equals(calculateArrivalAtNY(LocalDateTime.of(2019, 10, 15, 13, 0, 0), 13, 20))) {
System.err.println("测试失败!");
} else if (!LocalDateTime.of(2019, 11, 15, 13, 20, 0)
.equals(calculateArrivalAtNY(LocalDateTime.of(2019, 11, 15, 13, 0, 0), 13, 20))) {
System.err.println("测试失败!");
}
/*static LocalDateTime calculateArrivalAtNY(LocalDateTime bj, int h, int m){
return bj.plusHours(h).plusMinutes(m).atZone(ZoneId.of("Asia/Shanghai")).withZoneSameInstant(ZoneId.of("America/New_York")).toLocalDateTime();
}*/
//使用LocalDateTime或ZonedLocalDateTime时,我们要使用DateTimeFormatter进行格式化显示
ZonedDateTime zdt = ZonedDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm ZZZZ");
System.out.println(dtf.format(zdt));
DateTimeFormatter zhDtf = DateTimeFormatter.ofPattern("yyyy MMM dd EE HH:mm", Locale.CHINA);
System.out.println(zhDtf.format(zdt));
DateTimeFormatter usDtf = DateTimeFormatter.ofPattern("E, MMMM/dd/yyy HH:mm", Locale.US);
System.out.println(usDtf.format(zdt));
旧API转新API
把Date或Calendar转换为新API对象,可以通过toInstant()方法转换为Instant对象,再继续转换为ZoneDateTime
//Date -> Instant
Instant ins1 = new Date().toInstant();
System.out.println(ins1);
//Calendar -> Instant -> ZonedDatetime
Calendar calendar = Calendar.getInstance();
Instant ins2 = calendar.toInstant();
ZonedDateTime zdt = ins2.atZone(calendar.getTimeZone().toZoneId());
System.out.println(zdt);
//新转旧 借助long型时间戳做一个"中转"
ZonedDateTime zdt = ZonedDateTime.now();
long ts = zdt.toEpochSecond() * 1000;
//long -> Date
Date date = new Date(ts);
System.out.println(date);
//long -> Calendar
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTimeZone(TimeZone.getTimeZone(zdt.getZone().getId()));
calendar.setTimeInMillis(zdt.toEpochSecond() * 1000);
System.out.println(calendar.getTime());
最佳实践
//数据库中可以用BIGINT类型存储long型时间戳,用过一个方法为不桶用户显示本地时间
long ts = 1574208900000L;
System.out.println(timestampToString(ts, Locale.CHINA, "Asia/Shanghai"));
System.out.println(timestampToString(ts, Locale.US, "America/New_York"));
static String timestampToString(long epochMilli, Locale lo, String zoneId){
Instant ins = Instant.ofEpochMilli(epochMilli);
DateTimeFormatter f= DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT);
return f.withLocale(lo).format(ZonedDateTime.ofInstant(ins, ZoneId.of(zoneId)));
}
正则
//使用Pattern类对匹配的字符串进行提取
Pattern pattern = Pattern.compile("(\d{3,4})-(\d{7,8})");
System.out.println(pattern.matcher("010-12345678").matches());
System.out.println(pattern.matcher("021-12345").matches());
System.out.println(pattern.matcher("022#1234567").matches());
//获得Matcher对象:
Matcher matcher = pattern.matcher("010-12345678");
if(matcher.matches()){
String whole = matcher.group(0);
System.out.println(whole);
String area = matcher.group(1);
System.out.println(area);
String tel = matcher.group(2);
System.out.println(tel);
}
//非贪婪匹配
//1230000将前边数字和0分开
Pattern pattern = Pattern.compile("(\d+?)(0*)");
Matcher matcher = pattern.matcher("1230000");
if(matcher.matches()){
System.out.println("group1=" + matcher.group(1));
System.out.println("group2=" + matcher.group(2));
}
//分割字符串
System.out.println(Arrays.toString("a b c".split("\s")));
System.out.println(Arrays.toString("a b c".split("\s")));
System.out.println(Arrays.toString("a, b ;; c".split("[\,\;\s]+")));
//搜索字符串
String s = "the quick brown fox jumps over the lazy dog.";
Pattern p = Pattern.compile("\wo\w");
Matcher m = p.matcher(s);
while(m.find()){
String sub = s.substring(m.start(),m.end());
System.out.println(sub);
}
//替换字符串
String s = "The quicktt brown fox jumps over the lazy dog.";
String r = s.replaceAll("\s+"," ");
System.out.println(r);
//反向引用
String s = "the quick brown fox jumps over the lazy dog.";
String r = s.replaceAll("\s([a-z]{4})\s","<b>$1</b>");
System.out.println(r);
}
public static boolean isValidMobileNumber(String s){
return s.matches("^[1-9]\d{10}$");
}
public static boolean isValidEmail(String s){
return s.matches("^\w{3,}@[0-9a-zA-Z]{2,}\.(cn|com|net|org|edu)$");
}
public static boolean isValidPhoneNumber(String s){
return s.matches("^\d{3,4}-\d{7,8}$");
}
public static boolean isValidZipCode(String s){
return s.matches("\d{6}");
}
//xxxxxx yyyy MM dd 375 0 十八位
//xxxxxx yy MM dd 75 0 十五位
//十八位:^[1-9]d{5}(18|19|([23]d))d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)d{3}[0-9Xx]$
//十五位:^[1-9]d{5}d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)d{2}$
public static boolean isValidIdCard(String s){
return s.matches("^(\d{15}|\d{18}|\d{17}(\d|X|x))$");
}
最后
以上就是怕孤独刺猬为你收集整理的Java Util 类Java Util类的全部内容,希望文章能够帮你解决Java Util 类Java Util类所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复