正常情況下我們顯示時間用Date類就好了,傳輸時間的時候如果不規定長度可以直接將Date類型數據轉為String類型然后用getBytes()轉為byte[]進行傳輸就好了
這里我說的是規定長度的,這里規定傳輸要求:
年: 兩個字節
月,日,時,分,秒,星期: 各1個字節
這里需要注意的的我這里的星期是直接用 2表示了,正常情況下new Date()出來的數據是"Wed Sep 19 17:19:42 CST 2018"需要進行處理
先處理數據new Date()的
String system_time = TimeUtils.date2String (new Date());//系統時間
用工具類來統一時間格式調整為 "2018 9 18 15 26 13 2"所有的數據均由一個空格隔開
TimeUtils工具類
public class TimeUtils
{
/**
*Date轉換為String
**/
public static String date2String (Date date){
//2018-9-18
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// return sdf.format(date);
//2018-9-18 17:25:30
//SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//return sdf.format(date);
//2018-9-18 17:25:30 星期三
//SimpleDateFormat sdf= new SimpleDateFormat("yyyy MM dd HH mm ss EEE");
//return sdf.format(date);
//2018 9 18 17 25 30 3
SimpleDateFormat sdf= new SimpleDateFormat("yyyy MM dd HH mm ss u");
return sdf.format(date);
}
}
將格式統一到我們想要的格式,
若是由第三方傳來的額數據"2018-9-18 15:26:13 2"這樣格式的數據則不需要以上的工具類可直接用一下的方法
//這里的system_time是從第三方傳來的時間字符串,這里如果是做new Date需要進行String轉化
system_time = system_time.replaceAll("-"," ").replaceAll(":"," ");//用String的替換功能
接下來就是用byte數組封裝時間字符串
/**
* 時間字符串用byte[] 封裝
* @param date
* @return
*/
public static byte[] getByteTime(String date)
{
String[] timeString = date.split(" ");
int year = stringToInt(timeString[0]);
//年 2018 十六進制 7 E2 byte[] {7,-30 }
byte y1 = (byte) ((year >> 8) & 0xff);//年高八位
byte y2 = (byte) (year & 0xff);//年低八位
int month = stringToInt(timeString[1]);
int day = stringToInt(timeString[2]);
int hour = stringToInt(timeString[3]);
int minute = stringToInt(timeString[4]);
int second = stringToInt(timeString[5]);
int week = stringToInt(timeString[6]);
byte sum = (byte) ((y1 + y2 + month + day + hour + minute + second + week) & 0xff);//和校驗位,可加可不加
byte[] today = { y1, y2, (byte) month, (byte) day, (byte) hour, (byte) minute, (byte) second, (byte) week, sum};
return today;
}
public static int stringToInt(String s)
{
return Integer.parseInt(s);
}
這樣轉換后的時間就可以傳給需要的第三方平臺了,可以用socket通過tcp/ip協議傳輸了,一般這種時間的傳輸方式都用在與開發板信息的情況居多.僅供參考,歡迎批評指正.