Sunday, January 19, 2014

Date-Time as Directory in JAVA

There are times when you want to create directory structure as per the date and time.

For example if it is 2012 Jan 17 and time 10:38:22, then you have the requirement to create directory structure as
/2012/01/17/10/38/22

Of course it is possible to create the structure by manually extracting each components i.e year, month, day, etc from the object Date (methods to extract year, month, etc in Date object are now Deprecated) and Calendar (preferred to Date).

However recently I came with a method that easily formats the Calendar Object to represent as String in required format.


Examples:
  • Printing in the format YYYY/MM/DD

System.out.format(%tY/%tm/%td", c, c, c);


  • Printing in the format YYYY/MM/DD/HH/mm/SS

System.out.format("%tY/%tm/%td/%tl/%tM/%tS%n", c, c, c, c, c, c);

SEPARATING TOKEN CHARACTERS ( Like / , - ,  : ,  etc ) can be changed easily:
  • To Print as YYYY-MM-DD-HH:mm:SS

System.out.format("%tY-%tm-%td-%tl:%tM:%tS%n", c, c, c, c, c, c);

Formatting Options Available



      // %tY = Year
      // %ty = Year in 2 digit format
      // %tB = Month name
      // %tm = Month in 2 digits format
      // %td = Day of the month in format (02)
      // %te = Day of the month in format (2)
      // %tD = Date in format (02/02/1980)
      // %tl = Hours in 12 hour format
      // %tM = Minutes 00... 59
      // %tS = Seconds 00... 59
      // %tp = am/pm time


For saving the output into a variable instead of Printing directly


In the previous example the PrintStream has been delegated to system output stream (System.out). If however it is required to save the output to a variable, the PrintStream can be delegated to different stream so as to save to a variable. One of the method is by using ByteArrayOutputStream.

Example:

new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
ps.format("%tY/%tm/%td/%tl/%tM/%tS%n", c, c, c, c, c, c);
String content = baos.toString();


Here the output String is saved to the variable content.

Other Methods:

Apart from the method explained above, there are also other method to achieve this. One of the method is by using SimpleDateFormat. Its more simple to use this.

Example:

String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
strdate = sdf.format(c.getTime());

According to the requirement, the format String can be provided as argument to SimpleDateFormat() constructor.






No comments:

Post a Comment