0

I am working quite a lot with Unix timestamps. I installed the ts package, but I am not able to create a key-binding to show the conversion of a timestamp to natural date format.

I would like to be able to show the natural day of a marked timestamp. Is it possible to show in the minibuffer? Or at cursor point?. I don't want to replace or timestamp or insert in the current buffer.

1 Answer 1

0

Here's a simple-minded implementation that tries to detect the Unix timestamp at point. Assuming it finds one, it converts it to a human-readable date and prints it in the echo area, in the format specified by ts-default-format (which is defined in the ts package):


(require 'ts)

(defun ndk/ts-at-point ()
  (unless (looking-at "[0-9.]")
    nil)
  (let ((origin (point))
        beg end)
    (save-excursion
      (setq beg (+ origin (skip-chars-backward "0123456789."))))
    (save-excursion
      (setq end (+ origin (skip-chars-forward "0123456789."))))
    (list beg end)))

(defun ndk/show-date-at-point ()
  (interactive)
  (let* ((r (ndk/ts-at-point))
         (beg (nth 0 r))
         (end (nth 1 r))
         (unix_ts (buffer-substring beg end)))
    (message (ts-format (make-ts :unix (float (read unix_ts)))))))

The first function scans backwards and forwards trying to find the beginning and end of the timestamp that point is on. It's a bit fragile and simplistic and can be fooled easily, but it should do the job if you don't push it too far.

It is called by ndk/show-date-at-point to get the limits, which then reads that portion of the buffer, tries to convert it to a float and, if it succeeds, it assumes it's a Unix timestamp and converts it to a human-readable date, which is then echoed in the echo area with message.

To use it, put your cursor on a timestamp and say M-x ndk/show-date-at-point. Or bind it to a key to make it easy to call:

(global-set-key (kbd "C-c d") #'ndk/show-date-at-point)

C-c d is supposed to be unused by packages so that users can use it for their own purposes, but if you happen to use it already, choose another C-c <letter> binding.

2
  • Is working perfectly. I just need to use global-set-key instead of global-define-key)
    – TeXtnik
    May 31, 2021 at 13:15
  • Fixed - thanks for pointing it out.
    – NickD
    May 31, 2021 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.