Dates are complicated things. There are many different ways of storing them, and even more ways to present them. Converting them from one format to another always seems to challenge certain individuals. For this reason, the designers of most modern language libraries have taken it as part of their task to provide date handling utilities to deal with the nitty gritty of this task.

Most people appreciate the help and gladly use the built-in tools.

Most people.

In Java, if you wanted to print out the current date/time as: yyyymmddhhmmss, you could leverage the handy built-in utilities as follows:

  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
  String yyyymmddhhmmss = sdf.format(new Date());

It's painless and simple. Perhaps too simple to work properly...

J. R. found this beautiful java date formatter to do the same formatting as above in their codebase:

  String.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS", cal);

But he was confused as to why they needed their own format in the first place. So he spelunked into the bowels of the third Circle of Hell ("dates"), and found out why:

class MyDateString { 
  private static Calendar cal = Calendar.getInstance(); 

  public MyDateString() {} 

  public static final long getDateString(long currtime) { 
    if (currtime < 1000000) return -1L; 
    long rv = (currtime % 1000L); 
    rv += 1000L*((long)cal.get(Calendar.SECOND)); 
    rv += 100000L*((long)cal.get(Calendar.MINUTE)); 
    rv += 10000000L*((long)cal.get(Calendar.HOUR_OF_DAY)); 
    rv += 1000000000L*((long)cal.get(Calendar.DAY_OF_MONTH)); 
    rv += 100000000000L*((long)(1+cal.get(Calendar.MONTH))); 
    rv += 10000000000000L*((long)cal.get(Calendar.YEAR)); 
    return rv; 

This bit of ingenuity converts the decimal number of milliseconds since the dawn of Unix Time into a different decimal number with the layout:


...which can then be formatted by the String.format into a String with the same layout!

Pure genius!

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!