1. String type conversion time
1> String type time to type Date time
2> is converted into time stamp
3> is converted into a hexadecimal character string stamp
4> 16 hexadecimal string into a byte hexadecimal little-endian mode data
2. Date type time conversion
1> is converted to the time stamp
2> stamp is converted to a hexadecimal character string
3> 16 hexadecimal string into a byte hexadecimal little-endian mode data
Finishing Code:
package cn.xxs.dateDemo;
import java.lang.reflect.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
public class DateChange {
public static void main(String[] args) {
System.out.println(Arrays.toString(dateToStamp("2019-11-11 13:00:00")));
System.out.println(Arrays.toString(dateToStamp(new Date())));
}
/*
* 时间->时间戳->十六进制->小端模式byte数组
*/
public static byte[] dateToStamp(String time){
String stap = null;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date date;
try {
date = simpleDateFormat.parse(time);
long ts = date.getTime()/1000;//获取时间的时间戳
stap = Long.toHexString(ts);//十六进制
System.out.println("16进制字符串:"+stap);
} catch (ParseException e) {
e.printStackTrace();
}
String code0 = stap.substring(0, 2);
String code1 = stap.substring(2, 4);
String code2 = stap.substring(4, 6);
String code3 = stap.substring(6, 8);
byte[] timeByte = {(byte) getCode(code3),(byte) getCode(code2),(byte) getCode(code1),(byte) getCode(code0)};
return timeByte;
}
/*
* 时间->时间戳->十六进制->小端模式byte数组
*/
public static byte[] dateToStamp(Date date){
String stap = null;
long ts = date.getTime()/1000;//获取时间的时间戳
stap = Long.toHexString(ts);//十六进制
System.out.println("16进制字符串:"+stap);
String code0 = stap.substring(0, 2);
String code1 = stap.substring(2, 4);
String code2 = stap.substring(4, 6);
String code3 = stap.substring(6, 8);
byte[] timeByte = {(byte) getCode(code3),(byte) getCode(code2),(byte) getCode(code1),(byte) getCode(code0)};
return timeByte;
}
/**
* 将截取16进制两个字节字符串转换为byte类型
* @param str
* @return
*/
public static int getCode(String str){
int h = Integer.parseInt(str.substring(0,1),16);
int l = Integer.parseInt(str.substring(1,2),16);
// byte H = (byte) h;
// byte L = (byte) l;
// int s = H<<4 | L;
byte s = (byte) (((byte)h<<4) + (byte) l);
return s;
}
}
Test results: