代码片段
valten Lv4

AES 加密

后端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import org.apache.log4j.Logger;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;

/**
* @className: AESUtil
* @describe: 对称加密AES算法,前端cryptojs实现,后端Java实现
* @author: huangyuanli
* @date: 2019/2/21 10:22
**/
public class AESUtil {
private static final Logger LOG = Logger.getLogger(AESUtil.class);
private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
private static final String ALGORITHM = "AES";
private static final String CHARSET = "utf-8";
/**
* 建议为16位或32位
*/
private static final String KEY = "1234123412ABCDEF";
/**
* 必须16位
* 初始化向量IV不可以为32位,否则异常java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 16 bytes long
*/
private static final String IV = "ABCDEF1234123412";

// 加密
public static String encrypt(String context) {
try {
byte[] decode = context.getBytes(CHARSET);
byte[] bytes = createKeyAndIv(decode, Cipher.ENCRYPT_MODE);
return Base64.getEncoder().encodeToString(bytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

// 解密
public static String decrypt(String context) {
try {
Base64.Decoder decoder = Base64.getDecoder();
byte[] decode = decoder.decode(context);
byte[] bytes = createKeyAndIv(decode, Cipher.DECRYPT_MODE);
return new String(bytes, CHARSET);
} catch (Exception e) {
LOG.debug("context:" + context);
}
return null;
}

// 获取key & iv
public static byte[] createKeyAndIv(byte[] context, int opmode) throws Exception {
byte[] key = KEY.getBytes(CHARSET);
byte[] iv = IV.getBytes(CHARSET);
return cipherFilter(context, opmode, key, iv);
}

// 执行操作
public static byte[] cipherFilter(byte[] context, int opmode, byte[] key, byte[] iv) throws Exception {
Key secretKeySpec = new SecretKeySpec(key, ALGORITHM);
AlgorithmParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(opmode, secretKeySpec, ivParameterSpec);
return cipher.doFinal(context);
}
}

前端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//加密
getAesString: function(data){
var key = CryptoJS.enc.Utf8.parse("1234123412ABCDEF");
var iv = CryptoJS.enc.Utf8.parse("ABCDEF1234123412");
var encrypted = CryptoJS.AES.encrypt(data, key,
{
iv:iv,
mode:CryptoJS.mode.CBC,
padding:CryptoJS.pad.Pkcs7
});
//返回的是base64格式的密文
return encrypted.toString();
},
//解密
getDAesString: function(encrypted){
var key = CryptoJS.enc.Utf8.parse("1234123412ABCDEF");
var iv = CryptoJS.enc.Utf8.parse("ABCDEF1234123412");
var decrypted = CryptoJS.AES.decrypt(encrypted, key,
{
iv:iv,
mode:CryptoJS.mode.CBC,
padding:CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}

Base64与图片互转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
* 图片转为Base64字符串
**/
public class ConvertImgToBase64 {
public static void main(String[] args) {
//base64ToImg(base64, "D:/hczz.png");
//String base64Str = imgToBase64("D:/longmao.png");
//System.out.println(isImage(base64));
//writeToFile(base64Str, null, null);
}

public static String imgToBase64(String imgPath) {
InputStream in = null;
byte[] data = null;
String encode = null;
BASE64Encoder encoder = new BASE64Encoder();
try {
in = new FileInputStream(imgPath);
data = new byte[in.available()];
in.read(data);
encode = encoder.encode(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 去掉换行
if (StringUtils.isNotBlank(encode)) {
encode = encode.replaceAll("\r\n", "");
}
return encode;
}

public static boolean base64ToImg(String base64Str, String imgPath) {
if (StringUtils.isNotBlank(base64Str)) {
BASE64Decoder decoder = new BASE64Decoder();
OutputStream out = null;
try {
out = new FileOutputStream(imgPath);
byte[] b = decoder.decodeBuffer(base64Str);
out.write(b);
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}

private static void writeToFile(String str, String path, String fileName) {
if (StringUtils.isNotBlank(str)) {
try {
String newFileName = StringUtils.isBlank(fileName) ? "file" : fileName;
if (StringUtils.isNotBlank(path)) {
File dir = new File(path);
if (!dir.exists()) {
dir.createNewFile();
}
newFileName = path + File.separator + newFileName;
}

File file = new File(newFileName);
if (!file.exists()) {
file.createNewFile();
}

FileWriter fileWriter = new FileWriter(file.getName(), true);
fileWriter.write(str);
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public static boolean isImage(String imgBase64Str) {
if (StringUtils.isBlank(imgBase64Str)) {
return false;
} else {
ByteArrayInputStream byteArrayInputStream = null;

try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] byteArray = decoder.decodeBuffer(imgBase64Str);
byteArrayInputStream = new ByteArrayInputStream(byteArray);
BufferedImage bufImg = ImageIO.read(byteArrayInputStream);
if (bufImg == null) {
return false;
} else {
return true;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (byteArrayInputStream != null) {
try {
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return false;
}

}

ConcurrentHashmap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public class ConcurrentHashmapTest {

//循环次数
private static final int LOOP_COUNT = 10000000;
//线程数量
private static final int THREAD_COUNT = 10;
//元素数量
private static final int ITEM_COUNT = 1000;

private static Map<String, Long> normaluse() throws InterruptedException {
ConcurrentHashMap<String, Long> freqs = new ConcurrentHashMap<>(ITEM_COUNT);
ForkJoinPool forkJoinPool = new ForkJoinPool(THREAD_COUNT);
forkJoinPool.execute(() -> IntStream.rangeClosed(1, LOOP_COUNT).parallel().forEach(i -> {
//获得一个随机的Key
String key = "item" + ThreadLocalRandom.current().nextInt(ITEM_COUNT);
synchronized (freqs) {
if (freqs.containsKey(key)) {
//Key存在则+1
freqs.put(key, freqs.get(key) + 1);
} else {
//Key不存在则初始化为1
freqs.put(key, 1L);
}
}
}
));
forkJoinPool.shutdown();
forkJoinPool.awaitTermination(1, TimeUnit.HOURS);
return freqs;
}

private static Map<String, Long> gooduse() throws InterruptedException {
ConcurrentHashMap<String, LongAdder> freqs = new ConcurrentHashMap<>(ITEM_COUNT);
ForkJoinPool forkJoinPool = new ForkJoinPool(THREAD_COUNT);
forkJoinPool.execute(() -> IntStream.rangeClosed(1, LOOP_COUNT).parallel().forEach(i -> {
String key = "item" + ThreadLocalRandom.current().nextInt(ITEM_COUNT);
//利用computeIfAbsent()方法来实例化LongAdder,然后利用LongAdder来进行线程安全计数
freqs.computeIfAbsent(key, k -> new LongAdder()).increment();
}
));
forkJoinPool.shutdown();
forkJoinPool.awaitTermination(1, TimeUnit.HOURS);
//因为我们的Value是LongAdder而不是Long,所以需要做一次转换才能返回
return freqs.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().longValue())
);
}

public static void main(String[] args) throws InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start("normaluse");
Map<String, Long> normaluse = normaluse();
stopWatch.stop();
//校验元素数量
Assert.isTrue(normaluse.size() == ITEM_COUNT, "normaluse size error");
//校验累计总数
Assert.isTrue(normaluse.values().stream()
.mapToLong(l -> l).reduce(0, Long::sum) == LOOP_COUNT
, "normaluse count error");
stopWatch.start("gooduse");
Map<String, Long> gooduse = gooduse();
stopWatch.stop();
Assert.isTrue(gooduse.size() == ITEM_COUNT, "gooduse size error");
Assert.isTrue(gooduse.values().stream()
.mapToLong(l -> l)
.reduce(0, Long::sum) == LOOP_COUNT
, "gooduse count error");
System.out.println(stopWatch.prettyPrint());
}

}

通过反射给对象赋值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/**
* 解析反馈数据,并转换成对应的反馈对象
*
* @author xis
* @date 2020-01-14 17:39
**/
public class ResolveFeedbackData<T extends FbBaseInfo> {

public List<T> resolveFbData(Class<T> tClass, String sjxsm, List<String> sjxnr) {
if (CollectionUtils.isEmpty(sjxnr)) {
return null;
}
String[] sjxsms = sjxsm.split("\\|\\|");
// 数据项说明字段个数
int sjxsmLen = sjxsms.length;
// 数据项说明字段
String[] sFields = new String[sjxsmLen];
// 下划线连接改成驼峰命名
for (int i = 0; i < sjxsms.length; i++) {
String tmp = underlineToCamel(sjxsms[i].trim());
sFields[i] = tmp;
}
// 解析后的结果
return sjxnr.stream().collect(ArrayList::new, (list, sjx) -> {
String[] sjxs = sjx.split("\\|\\|");
// 数据内容长度
int sjxLen = sjxs.length;
if (sjxsmLen == sjxLen) {
// 获取源对象的所有属性
Field[] tFields = tClass.getDeclaredFields();
// 通过类的详情信息,创建目标对象 这一步等同于UserTwo target = new UserTwo();
T target = null;
try {
target = tClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < sjxs.length; i++) {
String sjxStr = sjxs[i].trim();
// 数据项说明
String sField = sFields[i];
// 循环对象的每一个属性
for (Field tField : tFields) {
// 判断源对象的属性名是否和目标对象的属性名一致
if (StringUtils.uncapitalize(sField).equals(tField.getName())) {
try {
// 属性的set方法名
String tMethodName = "set" + sField;
// 获得属性的set方法
Method tMethod = tClass.getMethod(tMethodName, tField.getType());
// 获取字段类型
String genericType = tField.getGenericType().toString();
// 字段值
Object sjxVal = null;
switch (genericType) {
case "class java.lang.String":
sjxVal = sjxStr.trim();
break;
case "class java.lang.Integer":
sjxVal = Integer.parseInt(sjxStr.trim());
break;
case "class java.lang.Double":
sjxVal = Double.parseDouble(sjxStr.trim());
break;
case "class java.util.Date":
// 获取注解的日期格式值
JSONField jsonField = tField.getAnnotation(JSONField.class);
String datePattern = "yyyy-MM-dd HH:mm:ss";
if (jsonField != null) {
datePattern = jsonField.format();
}
// 日期格式化
sjxVal = DateUtil.convertStringToDate(datePattern, sjxStr.trim());
break;
default:
break;
}
// 调用set方法,并将值作为参数传入
tMethod.invoke(target, sjxVal);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
list.add(target);
}
}, List::addAll);
}

/**
* @describe: 下划线转驼峰
* @param: str
* @return: String
* @author: huangyuanli
* @date: 2020/1/16 12:29
**/
public static String underlineToCamel(String str) {
if (str == null || "".equals(str.trim())) {
return "";
}
StringBuilder builder = new StringBuilder();
Arrays.asList(str.split("_")).forEach(temp -> builder.append(StringUtils.capitalize(temp)));
return builder.toString();
}

public static void main(String[] args) {
String str = "pass_code || start_place || end_place || order_create_time || order_begin_time || order_end_time || traveltype || city || driver_code";
// String[] split = str.split("\\|\\|");
// for (String s : split) {
// System.out.println(s.trim());
// }
// for (String s : split) {
// System.out.println(underlineToCamel(s.trim()));
// }

Class<?> tClass = DiDiOrder.class;
// Field[] declaredFields = tClass.getDeclaredFields();
// for (Field declaredField : declaredFields) {
// System.out.println(declaredField.getName());
// JSONField annotation = declaredField.getAnnotation(JSONField.class);
// if (annotation != null) {
// System.out.println(annotation.format());
// }
// }
List<String> objects = new ArrayList<>();
objects.add("13888848688 || 出发地1 || 目的地2 || 2019-12-21 09:10:32 || 2019-12-21 09:15:36 || 2019-12-21 09:55:39 || 出租车 || 上海市 || 13616678887");
objects.add("13888848688 || 出发地1 || 目的地2 || 2019-12-22 13:10:32 || 2019-12-22 13:15:36 || 2019-12-22 13:55:39 || 出租车 || 上海市 || 13936823456");
ResolveFeedbackData resolveFeedbackData = new ResolveFeedbackData();
List list = resolveFeedbackData.resolveFbData(tClass, str, objects);
for (Object o : list) {
System.out.println(o.toString());
}

}

static class DiDiOrder extends FbBaseInfo {
String passCode;
String startPlace;
String endPlace;
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
Date orderCreateTime;
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
Date orderBeginTime;
@JSONField(format = "yyyy-MM-dd HH:mm:ss")
Date orderEndTime;
String traveltype;
String city;
String driverCode;
String test;

public String getPassCode() {
return passCode;
}

public void setPassCode(String passCode) {
this.passCode = passCode;
}

public String getStartPlace() {
return startPlace;
}

public void setStartPlace(String startPlace) {
this.startPlace = startPlace;
}

public String getEndPlace() {
return endPlace;
}

public void setEndPlace(String endPlace) {
this.endPlace = endPlace;
}

public Date getOrderCreateTime() {
return orderCreateTime;
}

public void setOrderCreateTime(Date orderCreateTime) {
this.orderCreateTime = orderCreateTime;
}

public Date getOrderBeginTime() {
return orderBeginTime;
}

public void setOrderBeginTime(Date orderBeginTime) {
this.orderBeginTime = orderBeginTime;
}

public Date getOrderEndTime() {
return orderEndTime;
}

public void setOrderEndTime(Date orderEndTime) {
this.orderEndTime = orderEndTime;
}

public String getTraveltype() {
return traveltype;
}

public void setTraveltype(String traveltype) {
this.traveltype = traveltype;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getDriverCode() {
return driverCode;
}

public void setDriverCode(String driverCode) {
this.driverCode = driverCode;
}

public String getTest() {
return test;
}

public void setTest(String test) {
this.test = test;
}

@Override
public String toString() {
return "DiDiOrder{" +
"passCode='" + passCode + '\'' +
", startPlace='" + startPlace + '\'' +
", endPlace='" + endPlace + '\'' +
", orderCreateTime=" + orderCreateTime +
", orderBeginTime=" + orderBeginTime +
", orderEndTime=" + orderEndTime +
", traveltype='" + traveltype + '\'' +
", city='" + city + '\'' +
", driverCode='" + driverCode + '\'' +
", test='" + test + '\'' +
'}';
}
}
}

日期工具类

SimpleDateFormat

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
package com.hisign.xzxt2.common.utils;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

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

/**
* 日期处理共通方法
*
* @classname CommonUtils
* @author xzxt
* @date 2016年7月13日 下午4:23:40
*/
public class DateUtil extends DateUtils{

/**
* 日志
*/
private static Log log = LogFactory.getLog(DateUtil.class);

private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" };

/**
* 日期格式
*/
private static String datePattern = "yyyy-MM-dd";

/**
* 时间格式
*/
private static String timePattern = "HH:mm:ss";

/**
* 日期时间格式
*/
private static String datetimePattern = "yyyy-MM-dd HH:mm:ss";

/**
* 日期时间格式2
*/
private static String datetimePattern2 = "yyyyMMddHHmmss";

/**
* 中文日期格式
*/
private static String datePattern_CN = "yyyy年M月d日";

/**
* 中文日期时间格式 精确到分
*/
private static String datetimePattern_CN = "yyyy年M月d日H时m分";

/**
* 从message.properties中获取date.default_format对应的日期格式
* 默认日期格式:yyyy-MM-dd
* @author xzxt
* @date 2019/3/12 13:57
* @return 日期格式,默认:yyyy-MM-dd
**/
public static String getDatePattern() {
return datePattern;
}

/**
* Date类型的日期转化成String类型的日期
* 默认日期格式:yyyy-MM-dd
* @author xzxt
* @date 2019/3/12 14:00
* @param aDate 日期
* @return string类型的日期
**/
public static final String getDate(Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";

if (aDate != null) {
df = new SimpleDateFormat(datePattern);
returnValue = df.format(aDate);
}

return (returnValue);
}

/**
* string类型的日期转化成指定格式Date类型
* @author xzxt
* @date 2019/3/12 14:15
* @param aMask 指定的格式类型
* @param strDate string类型的日期
* @return Date类型的日期
**/
public static final Date convertStringToDate(String aMask, String strDate) throws ParseException {
SimpleDateFormat df = null;
Date date = null;
df = new SimpleDateFormat(aMask);

if (log.isDebugEnabled()) {
// debug状态时打印的日志
log.debug("converting '" + strDate + "' to date with mask '" + aMask + "'");
}

// 日期转化
try {
date = df.parse(strDate);
} catch (ParseException pe) {
throw new ParseException(pe.getMessage(), pe.getErrorOffset());
}

return date;
}

/**
* string类型的日期转化成默认Date类型的日期时间
* 默认格式:yyyy-MM-dd HH:mm:ss
* @author xzxt
* @date 2019/3/12 14:21
* @param strDate 需要转化的日期时间
* @return 默认格式的Date
**/
public static final Date convertStringToDateTime(String strDate) throws ParseException {
SimpleDateFormat df = null;
Date date = null;
df = new SimpleDateFormat(datetimePattern);

if (log.isDebugEnabled()) {
// debug状态时打印的日志
log.debug("converting '" + strDate + "' to date with mask '" + datetimePattern + "'");
}

// 日期时间转化
try {
date = df.parse(strDate);
} catch (ParseException pe) {
// log.error("ParseException: " + pe);
throw new ParseException(pe.getMessage(), pe.getErrorOffset());
}

return date;
}

/**
* 获取日期时间参数中的时间,返回格式为:HH:mm:ss
* @author xzxt
* @date 2019/3/12 14:27
* @param theTime 日期时间
* @return string类型的时间
**/
public static String getTimeNow(Date theTime) {
return getDateTime(timePattern, theTime);
}

/**
* 获取当前时间日历
* @author xzxt
* @date 2019/3/12 15:17
* @return 当前时间日历
**/
public static Calendar getToday() throws ParseException {
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat(datePattern);

// This seems like quite a hack (date -> string -> date),
// but it works ;-)
String todayAsString = df.format(today);
Calendar cal = new GregorianCalendar();
cal.setTime(convertStringToDate(todayAsString));

return cal;
}

/**
* Date类型日期时间转化成指定格式的string字符串日期时间
* @author xzxt
* @date 2019/3/12 15:18
* @param aMask 日期格式
* @param aDate 需要转化的日期时间
* @return string字符串日期时间
**/
public static final String getDateTime(String aMask, Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";

if (aDate == null) {
log.error("aDate is null!");
} else {
df = new SimpleDateFormat(aMask);
returnValue = df.format(aDate);
}

return returnValue;
}

/**
* Date类型日期时间转化成默认格式的string字符串日期时间
* 默认格式:yyyy-MM-dd HH:mm:ss
* @author xzxt
* @date 2019/3/12 15:18
* @param aDate 需要转化的日期时间
* @return string字符串日期时间
**/
public static final String getDateTime(Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";

if (aDate == null) {
log.error("aDate is null!");
} else {
df = new SimpleDateFormat(datetimePattern);
returnValue = df.format(aDate);
}

return (returnValue);
}

/**
* Date类型日期时间转化成默认格式的string字符串日期时间
* 默认格式:yyyy-MM-dd
* @author xzxt
* @date 2019/3/12 15:18
* @param aDate 需要转化的日期时间
* @return string字符串日期时间
**/
public static final String convertDateToString(Date aDate) {
return getDateTime(datePattern, aDate);
}

/**
* Date类型日期转化成指定格式的string字符串日期
* @author xzxt
* @date 2019/3/12 15:18
* @param pattern 日期格式
* @param aDate 需要转化的日期时间
* @return string字符串日期时间
**/
public static final String convertDateToString(String pattern, Date aDate) {
return getDateTime(pattern, aDate);
}

/**
* string字符串日期转化成默认格式的Date类型日期
* 默认格式:yyyy-MM-dd
* @author xzxt
* @date 2019/3/12 15:18
* @param strDate 需要转化的日期
* @return Date类型日期
**/
public static Date convertStringToDate(String strDate) throws ParseException {
Date aDate = null;

try {
if (log.isDebugEnabled()) {
log.debug("converting date with pattern: " + datePattern);
}

aDate = convertStringToDate(datePattern, strDate);
} catch (ParseException pe) {
log.error("Could not convert '" + strDate + "' to a date, throwing exception");
throw new ParseException(pe.getMessage(), pe.getErrorOffset());
}

return aDate;
}

/**
* 日期类型时间比较,如果date1>date2 则返回1,相等放回0,小于返回-1
* @author xzxt
* @date 2019/3/12 15:29
* @param date1 日期1
* @param date2 日期2
* @return date1>date2 则返回1,相等放回0,小于返回-1
**/
public static int compareDate(Date date1, Date date2) {
String d1 = getDateTime(datePattern, date1);
String d2 = getDateTime(datePattern, date2);

if (d1 == null && d2 != null) {
return -1;
} else if (d1 != null && d2 == null) {
return 1;
} else if (d1 == null && d2 == null) {
return 0;
} else {
return d1.compareTo(d2);
}
}

/**
* 日期时间转化成中文的日期时间字符串,默认格式:yyy年M月d日H时m分
* @author xzxt
* @date 2019/3/12 15:32
* @param date Date类型时间
* @return 中文的日期时间字符串
**/
public static String convertDatetimeToChineseString(Date date) {
DateFormat df = new SimpleDateFormat(datetimePattern_CN);
String strDate = df.format(date);
return strDate;
}

/**
* 日期转化成中文的日期字符串,默认格式:yyy年M月d日
* @author xzxt
* @date 2019/3/12 15:32
* @param date Date类型时间
* @return 中文的日期时间字符串
**/
public static String convertDateToChineseString(Date date) {
DateFormat df = new SimpleDateFormat(datePattern_CN);
String strDate = df.format(date);
return strDate;
}

/**
* 计算2个时间的差
*
* @author xzxt
* @param endDate 结束时间
* @param beginDate 开始时间
* @return Integer类型的天数
**/
public static Integer getUnm(Date endDate, Date beginDate) {
Integer a = 0;
try {
Long days = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000) + 1;
a = days.intValue();
} catch (Exception e) {
log.error(e.getMessage());
a = 0;
}
return a;
}

/**
* string类型日期时间转化成默认格式的Date类型日期
* 默认格式:yyyy-MM-dd
* @author xzxt
* @date 2019/3/12 15:40
* @param time 转 date yyyy-dd-mm
* @return Date类型日期
**/
public static Date strToDate(String time) {
SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
Date dt = null;
try {
dt = sdf.parse(time);
} catch (Exception ex) {
log.error(ex.getMessage());
}
return dt;
}

/**
* Date类型日期转化成指定格式的string字符串日期
* 默认格式:yyyyMMddHHmmss
* @author xzxt
* @date 2019/3/12 15:18
* @param aDate 需要转化的日期时间
* @return string字符串日期时间
*/
public static final String convertDateToString2(Date aDate) {
return getDateTime(datetimePattern2, aDate);
}

/**
* 按照yyyy-MM-dd HH:mm:ss的格式,日期转字符串
* @author xzxt
* @date 2019/3/12 15:54
* @param date Date类型日期时间
* @return String类型的日期时间
**/
public static String date2Str(Date date) {
return date2Str(date, datetimePattern);
}

/**
* 按照参数format的格式,日期转字符串
* @author xzxt
* @date 2019/3/12 15:57
* @param date Date类型日期
* @param format 日期格式
* @return String类型的时间
**/
public static String date2Str(Date date, String format) {
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
} else {
return "";
}
}

/**
* Object类型日期型转化为Date类型日期,自动适配字符串格式
* 格式:{ "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }
* @author xzxt
* @date 2019/3/12 15:58
* @param str Object类型的时间
* @return Date类型日期
**/
public static Date parseDate(Object str) {
if (str == null){
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}

/**
* 日期加1天
* @author xzxt
* @date 2019/3/12 16:06
* @param day Date类型日期
* @return Date类型日期
**/
public static Date toNextDay(Date day) {
Calendar calendar = new GregorianCalendar();
try {
Date date = convertStringToDate(convertDateToString(day));
calendar.setTime(date);
} catch (ParseException e) {
e.printStackTrace();
}
// 日期加1天
calendar.add(calendar.DATE, 1);
return calendar.getTime();
}

/**
* 获取相对当前的日期几天的日期
* @author xzxt
* @date 2018/11/22 15:13
* @param date 时间
* @param day int类型,可为负数
* @return 相对当前的日期几天的日期
*/
public static Date getRelativeDate(Date date, int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR) + day);
return cal.getTime();
}
}

DateTimeFormatter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
* 日期格式化工具类扩展
*
* @author huangyuanli
* @className DateUtils
* @package com.hisign.xzxt2.hxgc.clhx.utils
* @date 2021/8/31 11:40
**/
public class DateUtils {
/**
* 日期格式
*/
private static String datePattern = "yyyy-MM-dd";
/**
* 日期格式
*/
private static String datePattern2 = "yyyyMMdd";

/**
* 时间格式
*/
private static String timePattern = "HH:mm:ss";

/**
* 日期时间格式
*/
private static String datetimePattern = "yyyy-MM-dd HH:mm:ss";

/**
* 日期时间格式2
*/
private static String datetimePattern2 = "yyyyMMddHHmmss";

/**
* 中文日期格式
*/
private static String datePattern_CN = "yyyy年M月d日";

/**
* 中文日期时间格式 精确到分
*/
private static String datetimePattern_CN = "yyyy年M月d日H时m分";

/**
* 将日期字符串转成指定格式
* @param datetime 日期字符串
* @param srcPattern 源格式,就是传入日期字符串的格式
* @param targetPattern 目标格式
* @return 目标字符串
*/
public static String convertDate(String datetime, String srcPattern, String targetPattern) {
if (StringUtils.isEmpty(datetime)) {
return "";
}
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(srcPattern);
LocalDate ld = LocalDate.parse(datetime, dtf);

DateTimeFormatter fa = DateTimeFormatter.ofPattern(targetPattern);
return ld.format(fa);
}

/**
* 将时间字符串转成指定格式
* @param datetime 时间字符串
* @param srcPattern 源格式,就是传入时间字符串的格式
* @param targetPattern 目标格式
* @return 目标字符串
*/
public static String convertDateTime(String datetime, String srcPattern, String targetPattern) {
if (StringUtils.isEmpty(datetime)) {
return "";
}
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(srcPattern);
LocalDateTime ld = LocalDateTime.parse(datetime, dtf);

DateTimeFormatter fa = DateTimeFormatter.ofPattern(targetPattern);
return ld.format(fa);
}

public static void main(String[] args) {
String d = convertDate("19370707", datePattern2, datePattern);
System.out.println(d);

String dt = convertDateTime("19370707080925", datetimePattern2, datetimePattern);
System.out.println(dt);

String dt2 = convertDateTime("1937-07-07 08:09:25", datetimePattern, datetimePattern_CN);
System.out.println(dt2);
}
}
  • 本文标题:代码片段
  • 本文作者:valten
  • 创建时间:2020-12-25 11:18:25
  • 本文链接:https://valtenhyl.github.io/技术教程/code-snippet/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论