简单记录一下Java开发常用的小技巧。
1、获取指定时间的时间戳
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
try {
String dateStr = "2020-09-09 11:20:30";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt = df.parse(dateStr);
Timestamp ts = new Timestamp(dt.getTime());
System.out.println(dt.getTime());//1599621630000
System.out.println(ts.getTime());//1599621630000
} catch (ParseException e) {
e.printStackTrace();
}
}
}
2、获取当前时间的时间戳
import java.sql.Timestamp;
import java.util.Date;
public class Main {
public static void main(String[] args) {
try {
Date dt = new Date();
Timestamp ts = new Timestamp(dt.getTime());
System.out.println(dt.getTime());//1604909251372
System.out.println(ts.getTime());//1604909251372
} catch (Exception e) {
e.printStackTrace();
}
}
}
3、时间对象格式化输出
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
try {
Date dt = new Date();
SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df1.format(dt));//2020-11-09
System.out.println(df2.format(dt));//2020-11-09 16:07:31
} catch (Exception e) {
e.printStackTrace();
}
}
}
4、查找某字符在字符串中正数或倒数,且在第几个中出现的位置
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
正数例子:
import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
try {
String target = "AAA_BBB_CCC_DDD_EEE_FFF";
int startIndex = StringUtils.ordinalIndexOf(target, "_", 1);// 查找"_"在字符串中出现的第1个的位置
int endIndex = StringUtils.ordinalIndexOf(target, "_", 2);// 查找"_"在字符串中出现的第2个的位置
String result = target.substring(startIndex + 1, endIndex);
System.out.println(result);// BBB
} catch (Exception e) {
e.printStackTrace();
}
}
}
倒数例子:
import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
try {
String target = "AAA_BBB_CCC_DDD_EEE_FFF";
int startIndex = StringUtils.lastOrdinalIndexOf(target, "_", 2);// 查找"_"在字符串中出现的倒数第2个的位置
int endIndex = StringUtils.lastOrdinalIndexOf(target, "_", 1);// 查找"_"在字符串中出现的倒数第1个的位置
String result = target.substring(startIndex + 1, endIndex);
System.out.println(result);// EEE
} catch (Exception e) {
e.printStackTrace();
}
}
}
5、服务端进行HTTP请求,出现报错“java.lang.IllegalArgumentException: Illegal character in query at index”,可能是查询参数是中文的原因,将其进行URL编码即可
bookName = URLEncoder.encode(bookName,"UTF-8");
6、复制实体类属性值到视图类,源实体类与目标实体类需有相同属性
BeanUtils.copyProperties(productPo, productDto);
Class cls = productDto.getClass();
Field[] fields = cls.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
ReflectionUtils.makeAccessible(field);
configs.put(field.getName(), String.valueOf(field.get(productDto)).equals("1") ? true : false);
}