Formatting current system date in Common Lisp
Asked Answered
N

2

5

I am trying to get the current system date in Common Lisp through following function

(defun current-date-string ()
  "Returns current date as a string."
  (multiple-value-bind (sec min hr day mon yr dow dst-p tz)
                       (get-decoded-time)
    (declare (ignore sec min hr dow dst-p tz))
    (format nil "~A-~A-~A" yr mon day)))

Unfortunately I am getting the current date in this format "2014-1-2". However actually I need this format "2014-01-02". Is any way we can change the format? I tried replacing nil with yyyy-mm-dd but no luck. However my machine clock shows the date format is "2014-01-02".

Nita answered 2/1, 2014 at 3:10 Comment(0)
P
9

What you need is

(format nil "~4,'0d-~2,'0d-~2,'0d" yr mon day)

~2,'0d means:

  • d: decimal output (instead of your generic a)
  • 2: 1st argument: width
  • '0: 2nd argument: pad char 0

I suggest that you read up on Formatted Output; format is a very powerful tool.

Purvey answered 2/1, 2014 at 3:50 Comment(1)
Ah I understand. It will run in SBCL if I use unused variables for _, but then of course it gives warnings and it is indeed, in my opinion, "untidy". I'll remove it since I agree that I would therefore prefer the more idiomatic approach.Brunei

© 2022 - 2024 — McMap. All rights reserved.