1.根据星期几来获取日期
在这里插入代码片
public static Date getDateByWeek(int week){
List<Date> ds = getWeekDateList();
return ds.get(week-1);
}
public static List<Date> getWeekDateList() {
SimpleDateFormat s = new SimpleDateFormat("YYYY-MM-dd");
Calendar cal = Calendar.getInstance();
// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
cal.setFirstDayOfWeek(Calendar.MONDAY);
// 获得当前日期是一个星期的第几天
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayWeek == 1) {
dayWeek = 8;
}
// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);
Date mondayDate = cal.getTime();
cal.add(Calendar.DATE, 4 + cal.getFirstDayOfWeek());
Date sundayDate = cal.getTime();
List<Date> lDate = new ArrayList<>();
lDate.add(mondayDate);
Calendar calBegin = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calBegin.setTime(mondayDate);
Calendar calEnd = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calEnd.setTime(sundayDate);
//测试此日期是否在指定日期之后
while (sundayDate.after(calBegin.getTime())) {
// 根据日历的规则,为给定的日历字段添加或减去指定的时间量
calBegin.add(Calendar.DAY_OF_MONTH, 1);
lDate.add(calBegin.getTime());
}
return lDate;
}
2 获取当前系统时间的本周的日期和星期
在这里插入代码片
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
calendar.add(Calendar.DAY_OF_WEEK, -1);
}
List<WeekDayVo> list = new ArrayList<>();
for (int i = 0; i < 7; i++) {
// dates[i] = dateFormat.format(calendar.getTime());
WeekDayVo weekDayVo = new WeekDayVo();
//weekDayVo.setWeekDayStr(DateUtils.getWeekOfDate()String.valueOf(calendar.get(Calendar.DAY_OF_WEEK)));
weekDayVo.setWeekDayStr(DateUtils.getWeekOfDate(calendar.getTime()));
weekDayVo.setWeekDayDate(dateFormat.format(calendar.getTime()));
list.add(weekDayVo);
logger.info("++" + weekDayVo.getWeekDayStr());
calendar.add(Calendar.DATE, 1);
}
//vo对象
public class WeekDayVo {
private String weekDayStr = "";
private String weekDayDate ;
private String isNowDay = "";
public void setWeekDayStr(String weekDayStr) {
this.weekDayStr = weekDayStr;
}
public String getWeekDayStr() {
return weekDayStr;
}
public String getWeekDayDate() {
return weekDayDate;
}
public void setWeekDayDate(String weekDayDate) {
this.weekDayDate = weekDayDate;
}
@Override
public String toString() {
return "WeekDayVo{" +
"weekDayStr='" + weekDayStr + '\'' +
", weekDayDate=" + weekDayDate +
'}';
}
}
- 定时任务记录
@Scheduled(cron = "0 5 0 * * ?")//每天零点5分执行
public void updateUpload(){
Integer uploadLimitDaysInt = 0;
try{
BigDecimal uploadLimitDays = new BigDecimal(ToolsUtils.getSysKeyValue("fil_machine_upload").toString());
uploadLimitDaysInt = uploadLimitDays.intValue();
uploadLimitDaysInt = -1 * uploadLimitDaysInt;
}
catch (Exception ex)
{
logger.error("定时器上架矿机发生错误" + ex.getMessage());
}
if(uploadLimitDaysInt < 0)
{
scEcomOrdersService.updateUpload(uploadLimitDaysInt);
}
}
4 前端加时间判定
var myDate = new Date();
var now11 = new Date();
var year = now11.getFullYear(); //得到年份
var month = now11.getMonth()+1;//得到月份
var date = now11.getDate();
if(myDate.valueOf() >= new Date(year+"/"+month+"/"+date+" 9:00:00").valueOf() && myDate.valueOf() <= new Date(year+"/"+month+"/"+date+" 11:00:00").valueOf()){
window.location.href = "${webpath}/weixin/cart";
}else{
mui.alert("当前时间不可以预订!");
return false;
}
String类型键值对取值通用
public static Map<String, String> getMap(String params) {
HashMap<String, String> map = new HashMap<>();
int start = 0, len = params.length();
while (start < len) {
int i = params.indexOf('&', start);
if (i == -1) {
i = params.length(); // 此时处理最后的键值对
}
String keyValue = params.substring(start, i);
int j = keyValue.indexOf('=');
String key = keyValue.substring(0, j);
String value = keyValue.substring(j + 1, keyValue.length());
map.put(key, value);
if (i == params.length()) {
break;
}
start = i + 1; // index+1 为下一个键值对的起始位置
}
return map;
}
public static void main(String[] args) throws Exception {
String str = "k1=v1&k2=v2&k3=v3&k4=";
Map<String, String> map = getMap(str);
String k11 = map.get("k1");
System.out.println(k11);
//map.forEach((k, v) -> System.out.println(k + " -> " + v));
}
5 java判断小数点后2位
//金额验证
public static boolean isNumber(String str) {
Pattern pattern = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
Matcher match = pattern.matcher(str);
if (match.matches() == false) {
return false;
} else {
return true;
}
}
GET请求拼接url
public String urlSplicing(Map<String, Object> map, String url) {
StringBuilder builder = new StringBuilder(url);
boolean isFirst = true;
for (String key : map.keySet()) {
String value = String.valueOf(map.get(key));
if (key != null && value != null) {
if (isFirst) {
isFirst = false;
builder.append("?");
} else {
builder.append("&");
}
builder.append(key)
.append("=")
.append(value);
}
}
return builder.toString();
}
新建线程池
@Test
public void newMethod() throws InterruptedException {
/**
* 开启一个线程池 默认线程是10个
* 使用默认线程工厂
* 拒绝策略为CallerRunsPolicy策略,让后面的线程先等待
*/
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10, 1000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10),Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());
//书写一个循环 模拟100个用户同时访问
for (int request = 0; request< 100;request ++){
//开启一个线程
threadPoolExecutor.execute(() ->{
System.out.println("开始执行...");
/**
* 睡10秒
*/
try {
Thread.sleep(1000L * 30);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("结束执行...");
});
}
//为了方便测试 我们让主线程睡一会
Thread.sleep(1000 * 1000);
}
文件流方式下载
public void downLoadFileCSV(String filePath, HttpServletResponse response) throws Exception {
File files = new File(filePath);
try (FileInputStream fileInputStream = new FileInputStream(files);
BufferedInputStream bis = new BufferedInputStream(fileInputStream);
BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
) {
String filename = new String(files.getName().getBytes("UTF-8"), "ISO8859-1");
// 设置文件输出类型
response.setContentType("application/octet-stream");
// 设置文件输出名称
response.setHeader("Content-disposition", "attachment; filename=" + "\"" + filename + "\"");
response.setHeader("Content-Length", String.valueOf(fileInputStream.getChannel().size()));
// 获取输入流
// 获取输出流
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.flush();
} catch (Exception e) {
log.error(e.getMessage(), e);
}finally {
files.delete();//删除临时文件
}
}
zip工具类
package com.links.middleware.integral.jump.wanglaoji.common;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* danyu
* 压缩文件工具类
*/
public class ZipUtil {
private static final Logger log = LoggerFactory.getLogger(ZipUtil.class);
/**
*
* 压缩指定路径的文件
* @param srcFilePath 待压缩文件路径
* @param zipPathFileName zip文件全路径名
* @param password 加密密码
* @return
*/
public static boolean zipFile(String srcFilePath, String zipPathFileName, String password){
try {
// 生成的压缩文件
ZipFile zipFile = new ZipFile(zipPathFileName);
ZipParameters parameters = new ZipParameters();
// 压缩级别
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
if(!StringUtils.isEmpty(password)){
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword(password);
}
// 要打包的文件夹
File currentFile = new File(srcFilePath);
File[] fs = currentFile.listFiles();
// 遍历test文件夹下所有的文件、文件夹
for (File f : fs) {
if (f.isDirectory()) {
zipFile.addFolder(f.getPath(), parameters);
} else {
zipFile.addFile(f, parameters);
}
}
return true;
} catch (ZipException e) {
e.printStackTrace();
log.error("压缩文件【"+srcFilePath+"】到路径【"+zipPathFileName+"】失败:\n"+e.getMessage());
return false;
}
}
/**
* @param zipFileFullName zip文件所在的路径名
* @param filePath 解压到的路径
* @param password 需要解压的密码
* @return
*/
public static boolean unZipFile(String zipFileFullName, String filePath,String updatePath,String newName, String password) {
try {
ZipFile zipFile = new ZipFile(zipFileFullName);
// 如果解压需要密码
if(StringUtils.isNotEmpty(password)&&zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
List fileHeaders = zipFile.getFileHeaders();
for (Object object : fileHeaders) {
log.info(JSON.toJSONString(object));
String jsonString = JSON.toJSONString(object);
JSONObject parseObject = JSON.parseObject(jsonString);
String fileName = parseObject.getString("fileName");
log.info("==========压缩包内的文件有"+fileName);
zipFile.extractFile(fileName, filePath);
zipFile.extractFile(fileName, updatePath, null, newName);
}
return true;
} catch (ZipException e) {
e.printStackTrace();
log.error("解压文件【"+zipFileFullName+"】到路径【"+filePath+"】失败:\n"+e.getMessage());
return false;
}
}
/**
* 添加文件到压缩文件中
* @param zipFullFileName zip文件所在路径及全名
* @param fullFileNameList 待添加的文件全路径集合
* @param rootFolderInZip 在压缩文件里的文件夹名
* @return
*/
public static boolean addFilesToZip(String zipFullFileName, List<String> fullFileNameList, String rootFolderInZip) {
try {
ZipFile zipFile = new ZipFile(zipFullFileName);
ArrayList<File> addFiles = new ArrayList<>();
for (String fileName:fullFileNameList) {
addFiles.add(new File(fileName));
}
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
if(StringUtils.isNotEmpty(rootFolderInZip)){
if(rootFolderInZip.endsWith("/")==false){
rootFolderInZip = rootFolderInZip+"/";
}
parameters.setRootFolderInZip(rootFolderInZip);
}
zipFile.addFiles(addFiles, parameters);
return true;
} catch (ZipException e) {
e.printStackTrace();
log.error("添加文件失败:\n"+e.getMessage());
return false;
}
}
/**
* 从压缩文件中删除路径
* @param zipFullFileName
* @param fileName
* @return
*/
public static boolean deleteFileInZip(String zipFullFileName, String fileName) {
try {
ZipFile zipFile = new ZipFile(zipFullFileName);
zipFile.removeFile(fileName);
return true;
} catch (ZipException e) {
e.printStackTrace();
log.error("删除文件失败:\n"+e.getMessage());
return false;
}
}
public static List<String> getZipFileName(String string, String compressedPassword) {
try {
ZipFile zipFile = new ZipFile(string);
List<String> list = new ArrayList<>();
// 如果解压需要密码
if(StringUtils.isNotEmpty(compressedPassword)&&zipFile.isEncrypted()) {
zipFile.setPassword(compressedPassword);
}
List fileHeaders = zipFile.getFileHeaders();
for (Object object : fileHeaders) {
log.info(JSON.toJSONString(object));
String jsonString = JSON.toJSONString(object);
JSONObject parseObject = JSON.parseObject(jsonString);
String fileName = parseObject.getString("fileName");
log.info("==========压缩包内的文件有"+fileName);
list.add(fileName);
}
return list;
} catch (ZipException e) {
e.printStackTrace();
}
return new ArrayList<>();
}
}
--------------------------
需要引入
<!-- zip包需要 -->
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.2</version>
</dependency>
java8 删选俩个list不同数据
//删选出不同数据
//过滤俩个list中相同的数据
List<PlaceAssociation> dataList = list.stream().parallel().filter(a -> placeAssociationList.stream()
.noneMatch(b -> Objects.equals(a.getPlotId(), b.getPlotId()) && Objects.equals(a.getPlotName(), b.getPlotName())
&& Objects.equals(a.getPositionY(), b.getPositionY()) && Objects.equals(a.getPositionX(), b.getPositionX())
)
).collect(Collectors.toList());