Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Well, today is another day when I was hit in the face by myself. The painful bug came to me. As soon as I changed the new function, the small problem appeared. The forehead

So, fortunately, my boss is a kind man. Uh;

Today’s is about being made a day by time.

Background: The project will encounter a lot of time, in various formats and types, but most of them are timestamp based. There are a variety of time and date formats, some of which do not match, may be different time zones, and some of which are UTC.

UTC

Coordinated universal time, also known as world unified time, world standard time, international coordinated time. Because of the different abbreviations for CUT and TUC, the compromise was called UTC.

Beijing time:

GM+8

Time zone +8, based on geographical location;

International time is eight hours ahead of Beijing, so most international systems use UTC Greenwich Mean Time.

On the basis of UTC, with a specific format, it’s hard to tell the time format gap;

For example: Beijing time

GMT: indicates the current date

1. How to convert UTC time into Beijing time (timestamp)?

In order to convert UTC to Beijing time, you essentially add back the 8 hours you lost, but you need to use the timestamp equivalent, otherwise you can easily make a mistake

  • Now convert UTC fixed format time to fixed timestamp –UTC
  • Returns the timestamp GMT+8, plus the 8-hour timestamp
  • Convert the existing timestamp to fixed format output
Public static final String HOUR_PATTERN = "YYYY-MM-DD HH: MM :ss"; public static DateTimeFormatter formatter = DateTimeFormatter.ofPattern(HOUR_PATTERN);Copy the code
*/ public static String utcSecondToBJTime(Long utcTime) {Calendar = Calendar.getInstance(); calendar.setTimeInMillis(utcTime * 1000L); calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 8); return formatter.format(LocalDateTimeUtils.convertDateToLDT(calendar.getTime())); } /** * fixed format time, @param format * @return */ public static String dateToTimeStamp(String date_str, String format) { try { SimpleDateFormat sdf = new SimpleDateFormat(format); return String.valueOf(sdf.parse(date_str).getTime() / 1000); } catch (Exception e) {log.error(" current time conversion Exception ", e); } return ""; } /** * public static String getDateToString(Long time) {if (time.equals(0L)) {return null; } return formatter.format(LocalDateTimeUtils.convertLongToLDT(time)); }Copy the code
Copy the code

It should be noted that the timestamp converted from the fixed format may already be Beijing time, if it is not added again;

System.currentTimeMillis()
Copy the code

The current timestamp information can be output directly