Research on time stamp related knowledge

Recently, I want to use a timestamp on the project to check against replay attacks (the time difference of N minutes is considered to be a replay attack and refused to be processed)

However, it is found that the time in the common "yyyy-MM-dd HH: mm: ss" format will have problems in each time zone.

The timestamp is to be able to switch between the time zones in a unified manner. Everyone is at the same physical moment.
You are the time zone of the East Eight District, and I am the time zone of the East Nine District. Your eight o'clock is exactly me 9 o'clock.

Implementation plan:
1. timestamp refers to Greenwich Mean Time (GMT) January 01, 1970 00: 00 minutes 00 seconds to the total number of seconds. At the same moment, the values ​​obtained at any place in the world are the same.
Java uses long currentTime = System.currentTimeMillis (); to achieve

		long currentTime = System.currentTimeMillis();
		System.out.println(currentTime);
		System.out.println(System.nanoTime());
		SimpleDateFormat dong8 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dong8.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
		Date date8 = new Date(currentTime);
		System.out.println(dong8.format(date8));
		
		SimpleDateFormat dong9 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dong9.setTimeZone(TimeZone.getTimeZone("GMT+09:00"));
		Date date9 = new Date(currentTime);
		System.out.println(dong9.format(date9));

Output

2019-07-10 15:29:16
2019-07-10 16:29:16

2. Use string with time zone

		//转换为东八区时间
		String str = "2019-07-10 19:09:32 GMT+10:00";
		try {
			SimpleDateFormat simpleDateFormat4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
			Date date4 = simpleDateFormat4.parse(str);
			System.out.println("转换为东八区时间:" + simpleDateFormat4.format(date4));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

Output

转换为东八区时间:2019-07-10 17:09:32 GMT+08:00
Published 331 original articles · 51 praises · 440,000 visits +

Guess you like

Origin blog.csdn.net/y41992910/article/details/95342060