Search code examples
dateformattingkdb+zero

Kdb: Pre-pend Leading Zero to String if Less Than 2 Digits


I've extracted year, day, month, hour, minute and second from a datetime atom. How can I add leading zeros to day, month, hour, minute and second where the number of digits is less than 2?

I have something like this:

  year:string`year$inDateTime;
  day:string`dd$inDateTime;
  if[1=(count day);day:("0",day)];
  month:string`mm$inDateTime;
  if[1=(count month);month:"0",month];
  hour:string`hh$inDateTime;
  if[1=(count hour);hour:"0",hour];
  minute:string`uu$inDateTime;  
  if[1=(count minute);minute:"0",minute];
  second:string`ss$inDateTime;
  if[1=(count second);second:"0",second];

But is there a cleaner way of accomplishing this?


Solution

  • This line should achieve what you're looking for:

    "0"^-2$string`dd`mm`hh`uu`ss$x
    

    if you're looking to assign your values, you can use this:

    `day`month`hour`minute`second set'"0"^-2$string`dd`mm`hh`uu`ss$x
    

    Hope that helps!