java 时间戳转化

时间:2022-02-26 18:00:20

前几天写东西的需要转化时间戳,就去看了下。写完了,就在这记录下

public class TestJob {
private static Calendar calendar = Calendar.getInstance();
private static Lock lock = new ReentrantLock();

public static void main(String[] args) throws ParseException {
//获取当前时间的年月日时分秒毫秒周
Date currentTime = new Date();
System.out.println(currentTime);
int[] res = formatDate2IntArray(currentTime);
for (int i =0;i<res.length;i++){
System.out.println(res[i]);
}
//获取当前毫秒
System.out.println(System.currentTimeMillis());


//把xx-xx-xx 这种格式的时间转化为时间戳
Long startTime = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");//小写的mm表示的是分钟
String dstr = "2017-5-21 12:00:01 002";
startTime = sdf.parse(dstr).getTime();
System.out.println(startTime);

}

public static int[] formatDate2IntArray(Date date) {
int[] result = new int[9];

try {
lock.lock();
calendar.setTime(date);
int year = calendar.get(1);
int mon = calendar.get(2) + 1;
int day = calendar.get(5);
int hour = calendar.get(11);
int min = calendar.get(12);
int sec = calendar.get(13);
int milli = calendar.get(14);
int wednesday = calendar.get(4);
int dyaOfWeek = calendar.get(7);
result[0] = year;
result[1] = mon;
result[2] = day;
result[3] = hour;
result[4] = min;
result[5] = sec;
result[6] = milli;
result[7] = wednesday;
result[8] = dyaOfWeek;
} finally {
lock.unlock();
}

return result;
}
}

获取年月日那个方法,是公司前辈封好的,我又加了周几的参数。其他的就可以直接用了。