自定义获取纳秒级时间戳
package com.zr.your;
import java.util.Date;
/**
* @date 2021/9/24 15:03
*/
public class TimeOrStamp {
public long timeTransStamp(String data,int ns){
long start = new Date().getTime();
String year = data.substring(0, 4);
String month = data.substring(4, 6);
String days = data.substring(6, 8);
String hh = data.substring(8, 10);
String mm = data.substring(10, 12);
String ss = data.substring(12, 14);
System.out.println(month);
int y = Integer.parseInt(year);
int m = Integer.parseInt(month);
int d = Integer.parseInt(days);
int h = Integer.parseInt(hh);
int min = Integer.parseInt(mm);
int s = Integer.parseInt(ss);
int day = 0;
//从1970年1月1日算
for (int i = 1970; i < y; i++) {
if ((i % 4 == 0 && i % 100 != 0 ) || i % 400 == 0) {
day += 366;
}else{
day += 365;
}
}
//多算一天
day = day - 1;
//根据月份计算目前到当年的多少天
boolean isRy = false;
if ((y % 4 == 0 && y % 100 != 0 ) || y % 400 == 0) {
isRy = true;
}else{
isRy = false;
}
for (int j = 1; j < m; j++) {
if (isRy) {
switch (j) {
case 1: day += 31;continue;
case 2: day += 29;continue;
case 3: day += 31;continue;
case 4: day += 30;continue;
case 5: day += 31;continue;
case 6: day += 30;continue;
case 7: day += 31;continue;
case 8: day += 31;continue;
case 9: day += 30;continue;
case 10: day += 31;continue;
case 11: day += 30;continue;
case 12: day += 31;continue;
}
}else{
switch (j) {
case 1: day += 31;continue;
case 2: day += 29;continue;
case 3: day += 31;continue;
case 4: day += 30;continue;
case 5: day += 31;continue;
case 6: day += 30;continue;
case 7: day += 31;continue;
case 8: day += 31;continue;
case 9: day += 30;continue;
case 10: day += 31;continue;
case 11: day += 30;continue;
case 12: day += 31;continue;
}
}
}
//00:00:00区分
if (h == 0) {
day += d;
}else{
day += (d-1);
}
//东八区 多加了8小时,减去
long D8 = 8*60*60*1000000000;
Long timeStamp = (long) (day * 24 * 60 * 60 + h * 60 * 60 + min * 60 + s) * 1000000000 + ns ;
timeStamp = timeStamp - D8;
System.out.println("timeStamp: " + timeStamp);
long end = new Date().getTime();
System.out.println("耗时: " + (end - start) + "ms");
return timeStamp;
}
/**
* 计算秒级时间差
* @param startTime
* @param endTime
* @return
*/
public long caculateTimeS(long startTime, long endTime) {
long l = startTime / 1000000;
long l1 = endTime / 1000000;
long l2 = l1 - l;
return l2;
}
/**
* 计算ns级时间差
* @param startTime
* @param endTime
* @return
*/
public long caculateTimeNS(long startTime, long endTime) {
long l = startTime;
long l1 = endTime;
long l2 = l1 - l;
return l2;
}
public static void main(String[] args) {
TimeOrStamp timeDemo = new TimeOrStamp();
timeDemo.timeTransStamp("20201231000000",5000000);
}
}