How to insert the date into vim

23

2

In vim you can execute comands with "!". You can combine that with "r" to insert the output into your current buffer.

:r!date
Fri Jul 20 09:39:26 SAST 2012

will insert the date into a file.

Now when I try to do some more interesting stuff like date with different format +%F. On the command line

$ date +%F
2012-07-20

In vim

:r!date "+%F"
message.to.followup.lstF

Which out puts the name of the file and puts F after it. some how the r!date "+%F" is being expanded in vim and not run on the command line. What do I need to do to run that so it puts the contents in vim.

Maybe vim has a better way to insert dates into files.

nelaaro

Posted 2012-07-20T07:50:50.143

Reputation: 9 321

possible duplicate: http://stackoverflow.com/questions/6344750/how-do-i-insert-current-time-into-a-file-using-vim

– Ciro Santilli 新疆改造中心法轮功六四事件 – 2014-10-14T08:59:59.990

Here is another valid response using <F3>. You will need to modify your vimrc to get any date format you like, automatized.

– nilon – 2019-09-05T15:20:11.890

Answers

21

Vim has an internal strftime() function. Try this (in insert mode):

<C-r>=strftime('%F')<CR>

Heptite

Posted 2012-07-20T07:50:50.143

Reputation: 16 267

1

And in normal mode this is the same (insert date at current position): "=strftime("%F")<CR>P (Source: http://vim.wikia.com/wiki/Insert_current_date_or_time)

– erik – 2015-06-25T11:54:25.923

1I am choosing your answer as it the most vim like way to do things. – nelaaro – 2012-07-23T07:18:40.250

19

I kept experimenting till I figured out that vim was expanding the "%" character. So just escape "\%" and every thing works as I expected.

:r!date "+\%F"
2012-07-20

Now I can put dates into files Like I would like to

:r!date "+\%F" -d "-2 day"
2012-07-18

nelaaro

Posted 2012-07-20T07:50:50.143

Reputation: 9 321

1+1 That you can use with other programs than date too, and hence its easier to remember than the internat "strftime"-thing. – math – 2012-07-25T07:59:11.750

10

Another method, without escaping, using system():

system('date +%F')

In INSERT mode:

<C-r>=system('date +%F')<CR>

In NORMAL mode:

:put=system('date +%F')<CR>

romainl

Posted 2012-07-20T07:50:50.143

Reputation: 19 227

1<C-r> is very useful, I wish I had spent more time reading the help in vim. – nelaaro – 2012-07-20T08:41:25.463

1It's never too late. – romainl – 2012-07-20T10:22:19.547