View Javadoc
1   package edu.jiangxin.apktoolbox.utils;
2   
3   import org.apache.logging.log4j.LogManager;
4   import org.apache.logging.log4j.Logger;
5   
6   import java.text.ParseException;
7   import java.text.SimpleDateFormat;
8   import java.util.Date;
9   
10  public class DateUtils {
11      private static final Logger LOGGER = LogManager.getLogger(DateUtils.class.getSimpleName());
12  
13      private static final String PATTERN = "yyyy-MM-dd HH:mm:ss";
14  
15      /**
16       * Convert timestamp in second to a date string
17       */
18      public static String secondToHumanFormat(long second) {
19          SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
20          try {
21              return sdf.format(new Date(second * 1000));
22          } catch (Exception e) {
23              LOGGER.warn("Can not convert timestamp to a date");
24              return "";
25          }
26      }
27  
28      public static String millisecondToHumanFormat(long millisecond) {
29          SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
30          try {
31              return sdf.format(new Date(millisecond));
32          } catch (Exception e) {
33              LOGGER.warn("Can not convert timestamp to a date");
34              return "";
35          }
36      }
37  
38      /**
39       * Convert date string to a timestamp in second
40       */
41      public static Long humanFormatToSecond(String dateString) {
42          try {
43              SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
44              Date date = sdf.parse(dateString);
45              return date.getTime() / 1000;
46          } catch (ParseException e) {
47              LOGGER.warn("Can not parse this date string");
48              return 0L;
49          }
50      }
51  
52      /**
53       * Convert date string to a timestamp in millisecond
54       */
55      public static Long humanFormatToMillisecond(String dateString) {
56          try {
57              SimpleDateFormat sdf = new SimpleDateFormat(PATTERN);
58              Date date = sdf.parse(dateString);
59              return date.getTime();
60          } catch (ParseException e) {
61              LOGGER.warn("Can not parse this date string");
62              return 0L;
63          }
64      }
65  
66      public static String getCurrentDateString() {
67          try {
68              SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
69              return dateFormat.format(new Date());
70          } catch (Exception e) {
71              LOGGER.error("getCurrentDateString error", e);
72          }
73          return null;
74      }
75  }