1.将String类型的时间转换
1>String类型时间转换为Date类型的时间
2>时间转换为时间戳
3>时间戳转换为16进制字符串
4>16进制字符串转换为16进制小端模式byte数据
2.将Date类型的时间转换
1>时间转换为时间戳
2>时间戳转换为16进制字符串
3>16进制字符串转换为16进制小端模式byte数据
整理代码:
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;
}
}
测试结果为: