Advertisement
Guest User

Format

a guest
Dec 13th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.10 KB | None | 0 0
  1.     public static void main(String... strings) {
  2.         // Old
  3.         final String old1 = DateFormat.format_yyyyMMdd(new Date());
  4.         final String old2 = DateFormat.format_yyyy_MM_dd(new Date());
  5.         // New
  6.         final String new1 = format(LocalDate.now(), YYMMDD_PATTERN);
  7.         final String new2 = format(LocalDate.now(), YY_MM_DD_PATTERN);
  8.         System.out.println(Objects.equals(old1, new1));
  9.         System.out.println(Objects.equals(old2, new2));
  10.        
  11.         long currentMs = System.currentTimeMillis();
  12.         DateFormat.format(currentMs);
  13.        
  14.     }
  15.    
  16.     /**************
  17.      * OLD SOURCE CLONE
  18.      **************
  19.      */
  20.      public static final int JavaDate_StartYear = 1900;
  21.     private static final String Zero = "0";
  22.     private static String format2DNumber(int n) {
  23.         return n > 9 ? String.valueOf(n) : (Zero + n);
  24.     }
  25.     public static String format_yyyyMMdd(Date d) {
  26.         if (d == null) {
  27.             return null;
  28.         }
  29.         StringBuilder buidler = new StringBuilder()
  30.                 .append(d.getYear() + JavaDate_StartYear)
  31.                 .append(format2DNumber(d.getMonth() + 1))
  32.                 .append(format2DNumber(d.getDate()));
  33. //                .append( getMillisecond( d ) );
  34.         return buidler.toString();
  35.     }
  36.  
  37.     public static String format_yyyy_MM_dd(Date d) {
  38.         if (d == null) {
  39.             return null;
  40.         }
  41.         StringBuilder buidler = new StringBuilder()
  42.                 .append(d.getYear() + JavaDate_StartYear)
  43.                 .append("_")
  44.                 .append(format2DNumber(d.getMonth() + 1))
  45.                 .append("_")
  46.                 .append(format2DNumber(d.getDate()));
  47. //                .append( getMillisecond( d ) );
  48.         return buidler.toString();
  49.     }
  50.     // End
  51.     /**************
  52.      * NEW SOURCE CLONE
  53.      **************
  54.      */
  55.     private static final DateTimeFormatter YYMMDD_PATTERN = DateTimeFormatter.ofPattern("yyyyMMdd");
  56.     private static final DateTimeFormatter YY_MM_DD_PATTERN = DateTimeFormatter.ofPattern("yyyy_MM_dd");
  57.  
  58.     public static final String format(TemporalAccessor temporal, DateTimeFormatter formatter) {
  59.         return formatter.format(temporal);
  60.     }
  61.     // End
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement